读取两个标记之间的线
Read lines between two markers
如何在两个标记之间一次读取文本文件的一个部分。
例如;
**<Start>**
code:2010
<Stop>
<Start>
code:2011
code:2013
**<Stop>**
让它一次打印一行:
*code:2010
code:2011
code:2013*
我正在使用 Python3。我试过查看 're',但我认为我离题太远了。我也在 windows 机器上,不相信 awk 或 sed 对我可用。
欢迎任何方向。谢谢!
类似这样的东西可能适用于您的示例,但老实说我还没有测试过它:
start = 0
textlist = []
with open('myfile') as f:
for line in f:
if '<STOP>' in line.upper():
start = 0
elif start:
textlist.append(line)
elif '<START>' in line.upper():
start = 1
print(''.join(textlist))
如果是 text/csv,您可以执行以下操作:
import csv
codes = []
with open('myfile.csv', newline='') as f:
reader=csv.reader(f)
for line in reader:
if "code:" in line:
codes.append([line])
with open('output.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(codes)
如何在两个标记之间一次读取文本文件的一个部分。 例如;
**<Start>**
code:2010
<Stop>
<Start>
code:2011
code:2013
**<Stop>**
让它一次打印一行:
*code:2010
code:2011
code:2013*
我正在使用 Python3。我试过查看 're',但我认为我离题太远了。我也在 windows 机器上,不相信 awk 或 sed 对我可用。 欢迎任何方向。谢谢!
类似这样的东西可能适用于您的示例,但老实说我还没有测试过它:
start = 0
textlist = []
with open('myfile') as f:
for line in f:
if '<STOP>' in line.upper():
start = 0
elif start:
textlist.append(line)
elif '<START>' in line.upper():
start = 1
print(''.join(textlist))
如果是 text/csv,您可以执行以下操作:
import csv
codes = []
with open('myfile.csv', newline='') as f:
reader=csv.reader(f)
for line in reader:
if "code:" in line:
codes.append([line])
with open('output.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(codes)