使用Python删除文件中的特定行假设我有一个满是昵称的文本文件。如何使用Python从该文件中删除特定的昵称?
3 回答
繁花不似锦
TA贡献1851条经验 获得超4个赞
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
千万里不及你
TA贡献1784条经验 获得超9个赞
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()
PIPIONE
TA贡献1829条经验 获得超9个赞
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)
添加回答
举报
0/150
提交
取消