0

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!

b1234
  • 63
  • 7
  • As an aside, don't do `[ for line in f.readlines()]`, just use `[ for line in f]`. Iterating over a file object iterates over lines without putting the whole file into a list. – juanpa.arrivillaga Jan 29 '18 at 23:21

1 Answers1

1

If you are wanting to write the last entries from various files to ONE unique file, you need to use the ‘a’ parameter (append) when opening the file you are writing to

How to append data to text file in python 2.7.11?

thefragileomen
  • 1,537
  • 8
  • 24
  • 40