I'm trying to read a file, look for a specific word and if a line contains that word, remove the line and send the remaining lines to a new file. Here's what I have but it is only finding one of the lines not all of them;
with open('letter.txt') as l:
for lines in l:
if not lines.startswith("WOOF"):
with open('fixed.txt', 'w')as f:
print(lines.strip(), file=f)
The problem is that when you do with open('fixed.txt', 'w') as f:
you basically overwrite the entire content of the file with that one next line. Either open the file in append mode a
...
with open('letter.txt') as l:
for lines in l:
if not lines.startswith("WOOF"):
with open('fixed.txt', 'a') as f:
print(lines.strip(), file=f)
... or (probably better) open the file in w
mode, but just once at the beginning:
with open('letter.txt') as l, open('fixed.txt', 'w') as f:
for lines in l:
if not lines.startswith("WOOF"):
print(lines.strip(), file=f)
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.