Aaeria
Aaeria

Reputation: 13

Python 2.7 - How do I remove lines in a text file longer than x amount?

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

Answers (1)

user7851115
user7851115

Reputation:

To approach your problem:

  1. Read in the lines of your file. (readlines)
  2. Filter your lines down to the ones shorter than or equal in length to x. (filter)
  3. Overwrite your file. You might rejoin your lines into a string before doing so. (join)
  4. Always close the file when you're done.

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

Related Questions