continue vs. pass in this IO reading and writing

kbtyo ahlusar.ahluwalia at gmail.com
Thu Sep 3 11:38:55 EDT 2015


On Thursday, September 3, 2015 at 11:27:58 AM UTC-4, Chris Angelico wrote:
> On Fri, Sep 4, 2015 at 1:05 AM, kbtyo <ahlusar.ahluwalia at gmail.com> wrote:
> > However, I am uncertain as to how this executes in a context like this:
> >
> > import glob
> > import csv
> > from collections import OrderedDict
> >
> > interesting_files = glob.glob("*.csv")
> >
> > header_saved = False
> > with open('merged_output_mod.csv','w') as fout:
> >
> >     for filename in interesting_files:
> >         print("execution here again")
> >         with open(filename) as fin:
> >             try:
> >                 header = next(fin)
> >                 print("Entering Try and Except")
> >             except:
> >                 StopIteration
> >                 continue
> 
> I think what you want here is:
> 
> except StopIteration:
>     continue
> 
> The code you have will catch _any_ exception, and then look up the
> name StopIteration (and discard it).
> 
> >             else:
> >                 if not header_saved:
> >                     fout.write(header)
> >                     header_saved = True
> >                     print("We got here")
> >                 for line in fin:
> >                     fout.write(line)
> >
> > My questions are (for some reason my interpreter does not print out any readout):
> >
> > 1. after the exception is raised does the continue return back up to the beginning of the for loop (and the "else" conditional is not even encountered)?
> >
> > 2. How would a pass behave in this situation?
> 
> The continue statement means "skip the rest of this loop's body and go
> to the next iteration of the loop, if there is one". In this case,
> there's no further body, so it's going to be the same as "pass" (which
> means "do nothing").
> 
> For the rest, I think your code should be broadly functional. Of
> course, it assumes that your files all have compatible headers, but
> presumably you know that that's safe.
> 
> ChrisA

Hi ChrisA:

Thank you for the elaboration. So, what I hear you saying is that (citing, "In this case, there's no further body, so it's going to be the same as "pass" (which 
means "do nothing")") that the else block is not entered. For exma

Do you mind elaborating on what you meant by "compatible headers?". The files that I am processing may or may not have the same headers (but if they do they should add the respective values only). 



More information about the Python-list mailing list