【发布时间】:2015-08-30 15:38:16
【问题描述】:
我需要迭代一个文件,在一个条件上停止迭代,然后在同一行使用另一个函数继续解析文件(这可能会改变,所以我不能只在前一个函数中添加内容)。
一个示例文件(file.txt):
1
2
3
4
5
6
7
8
9
我尝试做的功能:
def parse1(file, stop):
# 1st parsing function (Main function I am doing)
for line in file:
if line.strip() == stop:
# Stop parsing on condition
break
else:
# Parse the line (just print for example)
print(line)
def parse2(file):
# 2nd parsing function (Will be my own functions or external functions)
for line in file:
# Parse the line (just print for example)
print(line)
终端结果:
>>> file = open("file.txt")
>>> parse1(file, "4")
1
2
3
>>> parse2(file)
5
6
7
8
9
我的问题是当我查找条件时,第一个函数跳过了“4”行。
我怎样才能避免这种情况:我找到了取消最后一次迭代或返回一行的任何解决方案。
file.tell() 函数不适用于文件中的for。
我尝试使用 while + file.readline() 执行此操作,但它比文件上的 for 循环慢得多(而且我想解析数百万行的文件)。
是否有一个优雅的解决方案来保持for 循环的使用?
【问题讨论】:
-
你不能保留 parse1 中的 line 变量并将其传递给 parse2
-
这个想法对我自己的函数很好,但我可能会使用一些外部函数来代替
parse2,这些函数没有这样的参数。
标签: python python-3.x for-loop file-io