[英]How to proceed next line while reading specific line?
我得到了名为“ datafile”的文件,其中包含如下数据:
tag
12
22
33
tag
234
1
23
43
tag
8
tag
0
12
“标签”之间的数字数量不同。
我需要做的是访问“标签”之后的每个第一个(或第二个)数字(如果存在)。
我未完成的Python代码:
f = open('datafile', 'r')
for line in f.readlines():
line = line.strip()
if line == 'tag':
print('tag found!')
# how can I access next number here?
我如何进入for循环中的下一行?
使用馈入生成器的迭代器。
def getFirstSecond(browser):
for line in browser:
line = line.strip()
if line == 'tag':
first = next(browser).strip()
try:
second = next(browser).strip()
except StopIteration:
second = None
yield first, second if second != 'tag' else first, None
with open('datafile', 'r') as f:
browser = iter(f)
pairs = list(getFirstSecond(browser))
要回答您的问题,请使用next
功能进入下一行。
注意with
语句的使用; 这就是您应该打开文件的方式(确保完成后关闭文件)。
每当您遇到“标签”时,只需重置一个计数器会更容易:
k = 1 # or 2, or whatever
with open('datafile', 'r') as f:
since_tag = 0
for line in f:
line = line.strip()
if line == 'tag':
print('tag found!')
since_tag = 0
if since_tag == k:
print "kth number found: ", line
since_tag += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.