[Tutor] Creating one file out of all the files in a directory

Josep M. Fontana josep.m.fontana at gmail.com
Sun Nov 14 19:34:26 CET 2010


Thanks Alan,

<snip> why is it better to open the output file outside the entire
>> loop.
>
> Because you only need to open it once and leave it open.
> You are opening it each and every time which is wasteful.
> It could on some OSDS also lead to problems. And if you
> were writing a new file rather than appending it would overwrite
> the contents each time which would be bad.

Dah, yes, you are totally right and now that I think about it it seems
pretty obvious. Now, why didn't I think about it? That's the problem.


<snip>

> Just put the with statement for the output file outside the loop:

You mean like this? It seems to work.
...
with open('/Volumes/myPath2/output.txt', 'a') as output_file:
   for subdir, dirs, files in os.walk(path):
      for filename in files:
          if filename != '.DS_Store':
              with open(filename, 'r') as f:
                  data = f.read()
                  output_file.write( "\n\n<file
name=%s>\n\n%s\n\n</file>\n\n" % (filename, data) )

>
> BTW you could use a single write with:
>
> output_file.write( '\n\n<file name=%s>\n\n%s\n\n</file>\n\n" % (filename,
> data) )
>
> But thats largely a matter of personal style.

Well, since I don't have any personal style yet, I might as well go
with the style of good programmers I learn from. If you notice in the
revised code I introduced above, I replaced the single quote with a
double quote to match the double quote you had used at the end. This
was a typo, right?

Josep M.


More information about the Tutor mailing list