假设我有一个充满昵称的文本文件。如何使用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指针,然后截断以删除最后一次写入之后的所有内容。

其他回答

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

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)

按行号删除文件中的某一行。

用文件名和要删除的行号替换变量filename和line_to_delete。

filename = 'foo.txt'
line_to_delete = 3
initial_line = 1
file_lines = {}

with open(filename) as f:
    content = f.readlines() 

for line in content:
    file_lines[initial_line] = line.strip()
    initial_line += 1

f = open(filename, "w")
for line_number, line_content in file_lines.items():
    if line_number != line_to_delete:
        f.write('{}\n'.format(line_content))

f.close()
print('Deleted line: {}'.format(line_to_delete))

示例输出:

Deleted line: 3

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

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