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
I liked the fileinput approach as explained in this answer: Deleting a line from a text file (python)
Say for example I have a file which has empty lines in it and I want to remove empty lines, here's how I solved it:
Assuming your file is in the format of one nickname per line, use this.
First, open the file:
Next, get all your lines from the file:
Now you can close the file:
And reopen it in write mode:
Then, write your lines back, except the line you want to delete. You might want to change the
"\n"
to whatever line ending your file uses.At the end, close the file again.
I think if you read the file into a list, then do the you can iterate over the list to look for the nickname you want to get rid of. You can do it much efficiently without creating additional files, but you'll have to write the result back to the source file.
Here's how I might do this:
I'm assuming
nicknames.csv
contains data like:Then load the file into the list:
Next, iterate over to list to match your inputs to delete:
Lastly, write the result back to file:
Probably, you already got a correct answer, but here is mine. Instead of using a list to collect unfiltered data (what
readlines()
method does), I use two files. One is for hold a main data, and the second is for filtering the data when you delete a specific string. Here is a code:Hope you will find this useful! :)
In general, you can't; you have to write the whole file again (at least from the point of change to the end).
In some specific cases you can do better than this -
if all your data elements are the same length and in no specific order, and you know the offset of the one you want to get rid of, you could copy the last item over the one to be deleted and truncate the file before the last item;
or you could just overwrite the data chunk with a 'this is bad data, skip it' value or keep a 'this item has been deleted' flag in your saved data elements such that you can mark it deleted without otherwise modifying the file.
This is probably overkill for short documents (anything under 100 KB?).
Save the file lines in a list, then remove of the list the line you want to delete and write the remain lines to a new file