I have a file I read and if the line in file contains "something" it will save the file to another file and if then I am trying to save lines that doesn't contain it to a different file but it doesn't work. Any help is appreciated. I am still a beginner in Python, so sorry if I am missing something silly.
with open("my.txt", errors='ignore') as f:
lines = [l for l in f if "findme" in l]
nolines = [l for l in f if "findme" not in l]
with open("save.txt", 'a') as fi:
for listitem in lines:
fi.write(listitem)
with open("remaining.txt", 'a') as fu:
for listfail in nolines:
fu.write(listfail)
The problem is that after the first looping through the lines of the file, your file pointer points at the end of the file. One way to solve your issue is to set the pointer back to the beginning with file.seek(0)
, e.g.:
with open("my.txt", errors='ignore') as f:
lines = [l for l in f if "findme" in l]
f.seek(0) # reset the file pointer position to the beginning
nolines = [l for l in f if "findme" not in l]
with open("save.txt", 'a') as fi:
for listitem in lines:
fi.write(listitem)
with open("remaining.txt", 'a') as fu:
for listfail in nolines:
fu.write(listfail)
However, a better approach to the problem is to loop through the lines only once and write the lines on the go:
with open('my.txt', 'r', errors='ignore') as src_file, \
open('save.txt', 'a') as tgt1_file, \
open('remaining.txt', 'a') as tgt2_file:
for line in src_file:
print(line, file=tgt1_file if 'findme' in line else tgt2_file, end='')
this is shorter, clearer and more efficient both computation-wise (presumably faster, but have not tested) and memory-wise (as there is no need to create potentially large intermediate lists).
Note that the use of print()
here, makes this code actually run somewhat slower than the original approach. This can be easily fixed by reverting to file.write()
:
with open('my.txt', 'r', errors='ignore') as src_file, \
open('save.txt', 'a') as tgt1_file, \
open('remaining.txt', 'a') as tgt2_file:
for line in src_file:
(tgt1_file if 'findme' in line else tgt2_file).write(line)