[英]Why in python loop for line in file is not going through all lines after using readline before?
Why in python loop for line in file is not going through all lines after using readline before? 为什么在python循环中,在使用readline之前,文件中的行没有遍历所有行? How to achieve that after reading some line(s) for loop will go through all lines in file? 在读取循环的某些行后将如何遍历文件中的所有行,如何实现?
file = open("file.xyz", "r")
first_line = file.readline()
for line in file:
x,y,z = line.split()
Reading from a file changes the "internal pointer" to the file for the next read operation. 从文件读取将“内部指针”更改为文件,以进行下一个读取操作。 Try: 尝试:
file.seek(0)
before the for loop. 在for循环之前。
因为文件知道其位置file.tell
。
To return to the start of file
, use 要返回file
的开头,请使用
file.seek(0)
As to why this happens: reading from a file is a bit like playing a tape, with a read head that moves along the tape. 关于发生这种情况的原因:从文件读取有点像播放磁带,并且读取头沿磁带移动。 After you read a line from a file, the "read head" is now at the start of the next line. 从文件中读取一行后,“读取头”现在位于下一行的开头。 Using seek
lets you "rewind" and "fast-forward" to specified points. 使用seek
可以使您“快退”和“快进”到指定点。
Reference: Python docs . 参考: Python文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.