fpo*_*g01 0 python text for-loop
我希望这段代码能够创建list_of_rows2 list,然后运行for循环.为什么for循环没有被执行?这是怎么回事open?
infile = r"D:\temp.txt"
with open(infile) as file2:
list_of_rows2 = [x.split() for x in file2]
for x in file2:
print x
Run Code Online (Sandbox Code Playgroud)
是的,这是open有效的.它返回文件对象的迭代器.你只能迭代一次直到筋疲力尽.
列表解析中的第一次迭代耗尽了文件迭代器,因此当你再次检查它时,没有什么可以迭代的.
这样做的好处是不会将整个文件(有时可能很大)同时加载到内存中,从而使程序在内存中窒息.但是,您可以(如果需要)通过调用readlines文件对象的方法将文件加载到内存中:
with open(infile) as file2:
file2 = file2.readlines() # or list(file2)
list_of_rows2 = [x.split() for x in file2]
for x in file2:
print x
Run Code Online (Sandbox Code Playgroud)
另一种选择是file2.seek(0)在再次迭代之前通过调用来寻找文件到其起始位置.