简体   繁体   中英

Python: create new text file with only last item saved

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!

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM