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


当前回答

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

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

就是这样!在一个且只有一个循环中,你可以做同样的事情。这样会快得多。

我喜欢下面解释的文件输入方法: 从文本文件中删除一行(python)

例如,我有一个文件,其中有空行,我想删除空行,这是我如何解决它:

import fileinput
import sys
for line_number, line in enumerate(fileinput.input('file1.txt', inplace=1)):
    if len(line) > 1:
            sys.stdout.write(line)

注意:在我的例子中,空行长度为1

您可以使用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)

在第一次传递中读取行并在第二次传递中进行更改(删除特定行)的问题是,如果文件大小很大,则会耗尽RAM。相反,更好的方法是逐行读取,并将它们写入单独的文件,删除不需要的文件。我曾经在12- 50gb大的文件上运行过这种方法,RAM使用几乎保持不变。只有CPU周期显示正在进行的处理。