Reputation: 13
How do I remove lines in a text file longer than x amount? Then overwriting that file and saving only those lines that were x amount long.
f = open("file.txt","r")
lines = f.readlines()
f.close()
f = open("file.txt","w")
for line in lines:
if line!="ph5"+"\n":
f.write(line)
f.close()
but don't work for me, because my strings contains "ph5", it's not only ph5 by itself
Upvotes: 0
Views: 859
Reputation:
To approach your problem:
readlines
)x
. (filter
)join
)Edit:
Now that you've figured out how to write it on your own, I'll offer an example of how this looks in the real world with a more Pythonic approach, so you can see the method I was suggesting as well.
# Open the file, read the lines into a list, and truncate the file.
file = open("file.txt", "r+")
lines = file.readlines()
file.seek(0)
file.truncate()
# Filter out lines longer than 42 characters and write to them the file.
lines = filter(lambda line: len(line) <= 42, lines)
file.writelines(lines)
file.close()
Upvotes: 3