Let's say I have a text file full of nicknames. How can I delete a specific nickname from this file, using Python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
The best and fastest option, rather than storing everything in a list and re-opening the file to write it, is in my opinion to re-write the file elsewhere.
That's it! In one loop and one only you can do the same thing. It will be much faster.
here's some other method to remove a/some line(s) from a file:
Not a good solve if u put a whole file to memory, i know nowadays everyone have tons of memory, but consider if the file is several GB of logs or something.
Better way copy it line by line to a new file, than delete the first or something like that
Take the contents of the file, split it by newline into a tuple. Then, access your tuple's line number, join your result tuple, and overwrite to the file.
This is a "fork" from @Lother's answer (which I believe that should be considered the right answer).
For a file like this:
This fork from Lother's solution works fine:
Improvements:
with open
, which discard the usage off.close()
if/else
for evaluating if string is not present in the current lineIf you use Linux, you can try the following approach.
Suppose you have a text file named
animal.txt
:Delete the first line:
then