且构网

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

删除文件中的特定行(python)

更新时间:2023-12-03 19:08:34

假设您的文件格式为每行一个昵称,请使用此。

Assuming your file is in the format of one nickname per line, use this.

首先打开文件:

f = open("yourfile.txt","r")

接下来,从文件中获取所有行:

Next, get all your lines from the file:

lines = f.readlines()

现在可以关闭文件:

f.close()

并以写入方式重新打开它:

And reopen it in write mode:

f = open("yourfile.txt","w")

然后,将您的行写回,除了要删除的行。您可能需要将\\\
更改为文件使用的任何行。

Then, write your lines back, except the line you want to delete. You might want to change the "\n" to whatever line ending your file uses.

for line in lines:
  if line!="nickname_to_delete"+"\n":
    f.write(line)

最后再次关闭文件。

f.close()