using Python for deleting a specific line in a fil

2018-12-31 06:26发布

Let's say I have a text file full of nicknames. How can I delete a specific nickname from this file, using Python?

14条回答
裙下三千臣
2楼-- · 2018-12-31 07:11

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.

with open("yourfile.txt","r") as input:
    with open("newfile.txt","wb") as output: 
        for line in input:
            if line!="nickname_to_delete"+"\n":
                output.write(line)

That's it! In one loop and one only you can do the same thing. It will be much faster.

查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 07:11

here's some other method to remove a/some line(s) from a file:

src_file = zzzz.txt
f = open(src_file, "r")
contents = f.readlines()
f.close()

contents.pop(idx) # remove the line item from list, by line number, starts from 0

f = open(src_file, "w")
contents = "".join(contents)
f.write(contents)
f.close()
查看更多
何处买醉
4楼-- · 2018-12-31 07:13

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

查看更多
初与友歌
5楼-- · 2018-12-31 07:13

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.

查看更多
步步皆殇っ
6楼-- · 2018-12-31 07:14

This is a "fork" from @Lother's answer (which I believe that should be considered the right answer).


For a file like this:

$ cat file.txt 
1: october rust
2: november rain
3: december snow

This fork from Lother's solution works fine:

#!/usr/bin/python3.4

with open("file.txt","r+") as f:
    new_f = f.readlines()
    f.seek(0)
    for line in new_f:
        if "snow" not in line:
            f.write(line)
    f.truncate()

Improvements:

  • with open, which discard the usage of f.close()
  • more clearer if/else for evaluating if string is not present in the current line
查看更多
长期被迫恋爱
7楼-- · 2018-12-31 07:16

If you use Linux, you can try the following approach.
Suppose you have a text file named animal.txt:

$ cat animal.txt  
dog
pig
cat 
monkey         
elephant  

Delete the first line:

>>> import subprocess
>>> subprocess.call(['sed','-i','/.*dog.*/d','animal.txt']) 

then

$ cat animal.txt
pig
cat
monkey
elephant
查看更多
登录 后发表回答