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

Kushal Kumaran kushal.kumaran at gmail.com
Thu Nov 11 14:07:13 CET 2010


----- Original message -----
> Hi,
> 
> I'm trying to create a script to do the following. I have a directory
> containing hundreds of text files. I need to create a single file with
> the contents of all the files in the directory. Within that file,
> though, I need to create marks that indicate the division between the
> contents of each file that has wound up in that single file.
> 

Your current code adds the marker line to the original files.  Is that intended?

You can open the output file for writing by passing 'w' as the second argument to open.  You would do this before your directory-walking loop.  Then when you read the contents of any file, just write to your output file as well, along with your marker line.

> I got this far but I'm stumped to continue:
> 
> ----------------- code--------
> import os
> path = '/Volumes/DATA/MyPath'
> os.chdir(path)
> file_names = glob.glob('*.txt')

output_stream = open('outputfilename', 'w')

> for subdir, dirs, files in os.walk(path):
>         for file in files:
>                 f = open(file, 'r')
>                 text = f.readlines()

output_stream.writelines(text)
output_stream.write('______\n')

>                 f.close()
>                 f = open(file, 'a')
>                 f.write('\n\n' + '________________________________' + '\n')
>                 f.close()
> 

output_stream.close()

> ------------
> 
> What's missing here is obvious. This iterates over all the files and
> creates the mark for the division at the end of each file. There is
> nothing, however, to pipe the output of this loop into a new file.
> I've checked the different manuals I own plus some more on the
> internet but I can't figure out how to do what's left.
> 
> I could get by with a little help from my Tutor friends.
> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101111/bdb2f06a/attachment.html>


More information about the Tutor mailing list