且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除文件中的特定行?

更新时间:2023-12-03 18:54:52

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

First, open the file and get all your lines from the file. Then reopen the file in write mode and write your lines back, except for the line you want to delete:

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也不会.

You need to strip("\n") the newline character in the comparison because if your file doesn't end with a newline character the very last line won't either.