假设我有一个充满昵称的文本文件。如何使用Python从这个文件中删除特定的昵称?


当前回答

这是来自@Lother的答案的一个“分叉”(我相信这应该被认为是正确的答案)。

对于这样的文件:

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

Lother解决方案中的这个分支工作得很好:

#!/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()

改进:

使用open,丢弃了f.s close()的用法 更清晰的if/else用于计算当前行中是否存在字符串

其他回答

一般来说,你不能;您必须重新编写整个文件(至少从更改点到末尾)。

在某些特定的情况下,你可以做得比这个更好

如果所有的数据元素都是相同的长度,并且没有特定的顺序,并且您知道要删除的数据元素的偏移量,那么您可以将最后一项复制到要删除的数据元素之上,并在最后一项之前截断文件;

或者你可以用“这是坏数据,跳过它”的值覆盖数据块,或者在保存的数据元素中保留“此项已删除”的标记,这样你就可以在不修改文件的情况下标记它已删除。

对于短文档(小于100 KB的文档?)来说,这可能有点过分了。

如果您使用Linux,可以尝试以下方法。 假设你有一个名为animal.txt的文本文件:

$ cat animal.txt  
dog
pig
cat 
monkey         
elephant  

删除第一行:

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

然后

$ cat animal.txt
pig
cat
monkey
elephant

您可以使用re库

假设您能够加载完整的txt文件。然后定义一个不需要的昵称列表,然后用空字符串“”替换它们。

# Delete unwanted characters
import re

# Read, then decode for py2 compat.
path_to_file = 'data/nicknames.txt'
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')

# Define unwanted nicknames and substitute them
unwanted_nickname_list = ['SourDough']
text = re.sub("|".join(unwanted_nickname_list), "", text)

将文件行保存在一个列表中,然后从列表中删除要删除的行,并将剩余的行写入一个新文件

with open("file_name.txt", "r") as f:
    lines = f.readlines() 
    lines.remove("Line you want to delete\n")
    with open("new_file.txt", "w") as new_f:
        for line in lines:        
            new_f.write(line)

下面是其他一些从文件中删除/some行的方法:

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()