So, I have written a code that should write a text file using two other texts, which starts with a line of text from Text No1., then follows a line from Text No2., then follows a line of text from Text No1. etc. until at the end it should end with lines from the text file with the most lines, for example:
Text No1. lines: a, b, c, d
Text No2. lines: e, f, g, h, i, j, k
Text No3. lines (that should be written by program) a, e, b, f, c, h, d, i, j, k
But, at the moment, the code
def text1():
f = open("textnr1.txt","r", encoding="UTF-8")
for line in f:
y = line.split(".")
print(len(y))
f.close()
f = open("textnr2.txt","r", encoding="UTF-8")
for line in f:
k = line.split(".")
print(len(k))
f.close()
gar=max(len(k),len(y))
f = open("results.txt","a", encoding="UTF-8")
for i in range(gar):
if i<len(y):
f.append(y[i])
if i<len(k):
f.append(k[i])
f.close()
only works if those text files consist of only one line per text file. What should I modify?
CodePudding user response:
If both files are the same length you can simply use zip
to get lines from both files at the same time and then simply write them both to the third file (also use context managers):
with open('file1.txt') as f1, open('file2.txt') as f2, \
open('result.txt', 'w') as res:
for l1, l2 in zip(f1, f2):
res.write(f'{l1}\n{l2}')
CodePudding user response:
You should fix some mistakes in your code:
- When you iterate through lines, you calculate
len(y)
, butlen(y)
is always 1 (of course if your line does not contain.
). I suppose you wanted to uselen(y)
as "count of lines in your file". - You should use
write()
method instead ofappend()
.
def text1():
f = open("files/textnr1.txt", "r", encoding="UTF-8")
first_text_lines = f.readlines()
f.close()
f = open("files/textnr2.txt", "r", encoding="UTF-8")
second_text_lines = f.readlines()
f.close()
gar = max(len(first_text_lines), len(second_text_lines))
f = open("files/results.txt", "a", encoding="UTF-8")
for i in range(gar):
if i < len(first_text_lines):
f.write(first_text_lines[i])
if i < len(second_text_lines):
f.write(second_text_lines[i])
f.close()
CodePudding user response:
You can merge the inputs in a list comprehension by leveraging itertools' chain and zip_longest:
text1 = "abcd"
text2 = "efghijk"
from itertools import chain,zip_longest
r = [ *filter(None,chain.from_iterable(zip_longest(text1,text2)))]
print(r)
['a', 'e', 'b', 'f', 'c', 'g', 'd', 'h', 'i', 'j', 'k']
text1 and text2 could be your k and y lists or any iterables (even more than 2 if needed)
The above assumes that you have no empty lines in your input. To handle empty lines, you'll need a different fillvalue for the shorter inputs:
end = object()
r = [x for x in chain.from_iterable(zip_longest(text1,text2,fillvalue=end))
if x != end]
In your program, you could use it like this:
with open("results.txt","a", encoding="UTF-8") as f:
end = object()
merged = (x for x in chain.from_iterable( zip_longest(k,y,fillvalue=end))
if x != end)
f.writelines(merged)
CodePudding user response:
Currently you are overwriting your y and k variables for every line in file, so after the loop runs, they only have the last line.
if you need all the lines anyway, just do:
with open("textnr2.txt","r", encoding="UTF-8") as f:
k=f.readlines()
this will take care of f.close() for you, and is the recommended way. k will be a list of all lines in file.
you say that you need lines, but in your code you are splitting by periods. I will assume that is because you wanted to test the function and your multiline reading didn't work.
after you fix the file reading, the code for writing lines should probably work.