删除文件中的特定行(python) [英] Deleting a specific line in a file (python)
本文介绍了删除文件中的特定行(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个文本文件充满昵称,如何从该文件中删除一个特定的昵称?
Lets say I have a text file full of nicknames, how can I delete a specific nickname from that file?
推荐答案
假设您的文件格式为每行一个昵称,请使用此。
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()
这篇关于删除文件中的特定行(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文