【发布时间】:2020-12-12 16:49:36
【问题描述】:
我正在尝试删除文本文件中以某个字符串开头的每个单词。我不知道如何写入输出文件。
输入文件:
Lorem ipsum applePEAR
dolor appleBANANA sit
appleORANGE amet, consectetur
所需的输出文件:
Lorem ipsum
dolor sit
amet, consectetur
到目前为止我的方法:
with open(infile) as fin, open(outfile, "w+") as fout:
for line in fin:
ls = line.split()
for word in ls():
if word.startswith("apple"):
line.replace(word, "")
fout.write(line)
我认为这种方法的问题是替换行拆分列表中的单词,而不是行本身。
检查 Stackoverflow,我发现这个问题类似于:using Python for deleting a specific line in a file,除了“nickname_to_delete”是一个以字符串开头的单词。
【问题讨论】:
-
replace有拼写错误吗? -
刚刚更正了拼写错误,但仍然没有运气。
标签: python string list replace