使用Python删除文件中的特定行

使用Python删除文件中的特定行

假设我有一个满是昵称的文本文件。如何使用Python从该文件中删除特定的昵称?



慕斯王
浏览 4103回答 3
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("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+”)打开文件,并使用find重置f指针,然后截断以删除上次写入后的所有内容。

PIPIONE

最好和最快的选择,而不是把所有的东西存储在一个列表中,重新打开文件来写它,在我看来,在其他地方重写文件。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)就这样!在一个循环中,只有你可以做同样的事情。它会快得多。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python