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


当前回答

我喜欢这个使用fileinput和inplace方法的方法:

import fileinput
for line in fileinput.input(fname, inplace =1):
    line = line.strip()
    if not 'UnwantedWord' in line:
        print(line)

它比其他答案少一点啰嗦而且足够快

其他回答

解决这个问题的方法只有一个:

with open("target.txt", "r+") as f:
    d = f.readlines()
    f.seek(0)
    for i in d:
        if i != "line you want to remove...":
            f.write(i)
    f.truncate()

该解决方案以r/w模式(“r+”)打开文件,并使用seek重置f指针,然后截断以删除最后一次写入之后的所有内容。

我喜欢这个使用fileinput和inplace方法的方法:

import fileinput
for line in fileinput.input(fname, inplace =1):
    line = line.strip()
    if not 'UnwantedWord' in line:
        print(line)

它比其他答案少一点啰嗦而且足够快

获取文件的内容,用换行符将其分割成一个元组。然后,访问元组的行号,加入结果元组,并覆盖到文件。

首先,打开文件并从文件中获取所有的行。然后以写模式重新打开文件,写回你想要删除的行:

with open("yourfile.txt", "r") as f:
    lines = f.readlines()
with open("yourfile.txt", "w") as f:
    for line in lines:
        if line.strip("\n") != "nickname_to_delete":
            f.write(line)

您需要去掉比较中的换行符(“\n”),因为如果您的文件不以换行符结束,那么最后一行也不会以换行符结束。

这是来自@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用于计算当前行中是否存在字符串