I have wrote a little simple Python script that should read from 2 different text files and output the two lines in to a new text file also with some text in the front and the end of each line. It works with the bline
but for some reason it only reads the the first line in aline
.
import os
f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'r')
f3 = open('new_file_name.txt','w')
for aline in f1:
aline = aline.rstrip()
for bline in f2:
bline = bline.rstrip()
f3.write('\n'"start %s:%s end" % (aline, bline))
file1 input:
1234
5678
9012
file2 input:
5678
9012
3456
new txt file should be:
start 1234:5678 end
start 5678:9012 end
start 9012:3456 end
but instead it is:
start 1234:5678 end
start 1234:9012 end
start 1234:3456 end
Can anyone give me a hint?
You're looping through the first one and then looping through the second one. This means that you're creating a bunch of combinations.
What you can do is use the zip()
function between the two files.
for aline, bline in zip(f1, f2):
aline = aline.rstrip()
bline = bline.rstrip()
f3.write('\n'"start %s:%s end" % (aline, bline))
f1.close()
f2.close()
f3.close() # Remember to close!
What you need is to zip
both f1
and f2
so to get both of their values for each line at the same time and then write them to f3
:
with open('file1.txt') as f1, open('file2.txt') as f2, open('new.txt', 'w') as f3:
for a_line, b_line in zip(f1, f2):
f3.write(f'start {a_line.rstrip()}:{b_line.rstrip()} end\n')
Also it is suggested that you use context manager ( with
) to open files (it also automatically closes them when you exit out of the block).
file_1 = open('file1.txt', 'r').split('\n') file_2 = open('file2.txt', 'r').split('\n') file_3 = [] # as list so we can dump it all at once for segment in zip(file_1, file_2): file_3.append(f'start {segment[0]}:{segment[1]} end') open('file3.txt', 'w').write('\n'.join(file_3))
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.