我喜欢将原始文本文件的某些部分(可以在'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包含所有以“以字符串开头”和“以字符串结尾”开头的所有字符串。
每行的末尾都有一个字符,告诉计算机显示新行。我在这里假设“以字符串开头”和“以字符串结尾”在同一行上。如果不是这种情况,请在第一个if语句的正下方添加-“ id.append(ln [:])”-。
尝试
ln.endswith("ends with string"+'\n' )
要么
ln.endswith("ends with string"+'\n' +'\r')
with open('C:\\Py\\testing.txt','r') as fi:
id = []
x = 0
copy_line = False
for ln in fi:
if "starts with string" in ln:
copy_line = True
if copy_line:
id.append ( ln[:] )
if "ends with string" in ln :
copy_line = False
with open ('C:\\Py\\testing_out.txt', 'a', encoding='utf-8' ) as fo:
fo.write (",".join(id))
print(id)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句