我喜欢将原始文本文件的一部分(可以在“startswith”和“endswith”字符串之间识别)保存到一个新的文本文件中。
示例:输入文本文件包含以下行:
...abc…
...starts with string...
...def...
...ends with string...
...ghi...
...jkl...
...starts with string...
...mno...
...ends with string...
...pqr...
我有兴趣将以下行提取到输出文本文件中:
starts with string...def...ends with string
starts with string...mno...ends with string
我的以下代码返回空列表 []。请帮助更正我的代码。
with open('file_in.txt','r') as fi:
id = []
for ln in fi:
if ln.startswith("start with string"):
if ln.endswith("ends with string"):
id.append(ln[:])
with open(file_out.txt, 'a', encoding='utf-8') as fo:
fo.write (",".join(id))
print(id)
我希望 file.out.txt 包含所有以“以字符串开头”开头并以“以字符串结尾”结尾的字符串。