I have a set of .txt files (12) that I want to read and write to 3 output .txt files (so each output will have text from all 12 files).
I accomplish this with the following code, BUT the files do not overwrite what is already there, but append the text. I realize this may be due to me using "a" as append, but if I use "w", only the first document of my 12 gets written to each output.
The "truncate()" method seems to have no effect.
def WriteFiles():
# import library
import glob
# read file names
txt_files = glob.glob('input/*.txt')
output_files = glob.glob('output*')
# loop trough outputs & files and append
for index_out, output in enumerate(output_files):
for index_in, file in enumerate(txt_files):
with open(file, 'r+') as f, open(output, 'a') as o:
print('Writing input {} to output {}'.format(index_in, index_out))
o.truncate()
o.write(f.read())
You could simply open
the output file earlier, in the first for
loop. E.g.
for index_out, output in enumerate(output_files):
with open(output, 'w') as o:
for index_in, file in enumerate(txt_files):
with open(file, 'r+') as f:
print('Writing input {} to output {}'.format(index_in, index_out))
o.write(f.read())
This will only open and truncate each output file once, before the second for
loop starts, and the file
object will look after the current position in the output file.