就像标题一样简单,真的。但不知何故挣扎。用 boop 删除行beepboop bop Hey beepboopbopfile_path = "C:\\downloads\\test.txt"with open(file_path, "r") as f: lines = f.readlines()with open(file_path, "w") as f: for line in lines: if line.rfind("boop") >= 0: f.write(line)file_in.close()我不明白完全删除或清除该行的最佳方法。
2 回答
白板的微信
TA贡献1883条经验 获得超3个赞
您可以以读写模式打开文件并删除符合条件的行。
with open(file_path, "r+") as fp:
lines = fp.readlines()
fp.seek(0)
for line in lines:
if "boop" not in line:
fp.write(line)
fp.truncate()
seek重置文件指针。
慕码人8056858
TA贡献1803条经验 获得超6个赞
打开文件并读取其内容,然后再次打开文件,将行写入其中但不要包含“boop”的行:
path='path/to/file.txt'
with open(path, "r") as f:
lines = f.readlines()
with open(path, "w") as f:
for line in lines:
if line.strip("\n") != "boop":
f.write(line)
添加回答
举报
0/150
提交
取消