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


当前回答

在我看来,最好和最快的选择是在其他地方重写文件,而不是将所有内容存储在一个列表中并重新打开文件来写入。

with open("yourfile.txt", "r") as file_input:
    with open("newfile.txt", "w") as output: 
        for line in file_input:
            if line.strip("\n") != "nickname_to_delete":
                output.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()

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

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)

我喜欢这个使用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”),因为如果您的文件不以换行符结束,那么最后一行也不会以换行符结束。

你想从文件中删除特定的行,所以使用这个简短的代码片段,你可以很容易地删除任何带有句子或前缀(符号)的行。

with open("file_name.txt", "r") as f:
lines = f.readlines() 
with open("new_file.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("write any sentence or symbol to remove line"):
            new_f.write(line)