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

Josep M. Fontana josep.m.fontana at gmail.com
Thu Nov 11 13:08:11 CET 2010


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.

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')
for subdir, dirs, files in os.walk(path):
    for file in files:
        f = open(file, 'r')
        text = f.readlines()
        f.close()
        f = open(file, 'a')
        f.write('\n\n' + '________________________________' + '\n')
        f.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.

Josep M.


More information about the Tutor mailing list