【发布时间】:2016-06-15 23:14:32
【问题描述】:
我需要从下面的文本文件中提取值:
fdsjhgjhg
fdshkjhk
Start
Good Morning
Hello World
End
dashjkhjk
dsfjkhk
我需要提取的值是从头到尾。
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
copy = False
for line in infile:
if line.strip() == "Start":
copy = True
elif line.strip() == "End":
copy = False
elif copy:
outfile.write(line)
我使用的上面的代码来自这个问题: Extract Values between two strings in a text file using python
此代码将不包括字符串“开始”和“结束”,只是其中的内容。您将如何包含外围字符串?
【问题讨论】:
-
我会使用多行正则表达式 - 代码看起来也更容易
标签: python python-3.x