Reading/Writing Text from Multiple Files to Master File
<p>In the code below I'm trying to open a series of text files and copy their contents into a single file. I'm getting an error on the "os.write(out_file, line)" in which it asks me for an integer. I haven't defined what "line" is, so is that the problem? Do I need to specify somehow that "line" is a text string from the in_file? Also, I open the out_file through each iteration of the for-loop. Is that bad? Should I open it once at the beginning? Thanks!</p>

<pre><code>import os
import os.path
import shutil

# This is supposed to read through all the text files in a folder and
# copy the text inside to a master file.

#   This defines the master file and gets the source directory
#   for reading/writing the files in that directory to the master file.

src_dir = r'D:\Term Search'
out_file = r'D:\master.txt'
files = [(path, f) for path,_,file_list in os.walk(src_dir) for f in file_list]

# This for-loop should open each of the files in the source directory, write
# their content to the master file, and finally close the in_file.

for path, f_name in files:
    open(out_file, 'a+')
    in_file = open('%s/%s' % (path, f_name), 'r')
    for line in in_file:
        os.write(out_file, line)
    close(file_name)
    close(out_file)

print 'Finished'
</code></pre>
