[英]Iterating over a text file and returning a range of values in Python
I need to get a range of values from a large text file that contains epoch time stamps. 我需要从包含纪元时间戳的大文本文件中获取一系列值。 I am currently looping through the file for start/end points, retrieving the line numbers, then iterating over the list again to retrieve the range values.
我目前正在遍历文件中的起点/终点,检索行号,然后再次遍历列表以检索范围值。 This feels very inefficient because it involves looping over the list twice.
感觉效率很低,因为它涉及遍历列表两次。 Is there a better way?
有没有更好的办法?
start = '1509347040'
end = '1509347700'
with open('database.txt') as fp:
for i, line in enumerate(fp):
if start in line:
start=i
elif end in line:
end=i
break
for i, line in enumerate(fp):
if i >= start and i <= end:
print(i,line)
You can use a flag
variable to keep track of the moment you encountered start
. 您可以使用
flag
变量来跟踪遇到start
的时刻。 Something like this. 这样的事情。 This way you will traverse through the file only till the
end
(in the worst case, only once through the file). 这样,您将仅遍历文件直到
end
(在最坏的情况下,仅遍历文件一次)。
flag = 0
with open('database.txt') as fp:
for i, line in enumerate(fp):
if start in line:
flag = 1
elif end in line:
print(i,line)
break
if flag==1:
print(i,line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.