I am trying to create a single text file of all items from the last column from a series of other files, separated with new lines (so if I have 4 existing text files, the new file should have 4 rows).
The code I have is properly is creating a new file that has all the last items in the last column from a file:
with open('originalfile1.txt') as f:
lines = [line.strip().split()[-1] for line in f.readlines()]
with open('newtextfile.txt', 'w') as f:
f.write(' '.join(lines) + '\n' + ' ')
Without getting into the for loop to go over the files, just running this manually for the next file:
with open('originalfile2.txt') as f:
lines = [line.strip().split()[-1] for line in f.readlines()]
with open('10_stimtimes.txt', 'w') as f:
f.write(' '.join(lines) + '\n' +' ' + '\n' + ' ')
...overwrites the original output. And this:
with open('IAPS_id10_run1.txt') as f:
lines = [line.strip().split()[-1] for line in f.readlines()]
with open('10_stimtimes.txt', 'w') as f:
f.write(' '.join(lines) + '\n' + ' '.join(lines))
...writes the output of the last column from the second file twice and overwrites the output from the first file.
What am I doing incorrectly to be able to maintain the output from all files?
Thank you!