使用Python删除fi中的特定行

2024-04-24 07:04:50 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

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

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)

您需要在比较中strip("\n")换行符,因为如果您的文件没有以换行符结尾,那么最后一个line也不会。

最好和最快的选择,而不是把所有的东西都存储在一个列表中,然后重新打开文件来写它,在我看来,是在别处重新写文件。

with open("yourfile.txt", "r") as input:
    with open("newfile.txt", "w") as output: 
        for line in input:
            if line.strip("\n") != "nickname_to_delete":
                output.write(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指针,然后截断以删除上次写入后的所有内容。

相关问题 更多 >