简体   繁体   English

为什么在python循环中,在使用readline之前,文件中的行没有遍历所有行?

[英]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.

相关问题 使用readline()python后在各行中移动 - move through lines after using readline() python 在“for line in data”循环中使用.readline()将多行文件分配给多个变量 - Assigning multiple lines of a file to multiple variables using .readline() while in a “for line in data” loop Python-readline()循环将所有行放入字典中的相同值槽中 - Python - readline() loop placing all lines into same value slot in dictionary for 循环如何在不使用 readline() 的情况下打印文本文件的所有行 - How does for loop print all the line of a text file without using readline() Python,遍历文件中的行; 如果line等于另一个文件中的行,则返回原始行 - Python, loop through lines in a file; if line equals line in another file, return original line 删除特定行python之前的所有行 - Deleting all lines before a specific line python 在对文本文件中的所有行使用split()之后,我的意图是在最后一个元素之前的每一行中添加“,” - After using split() for all lines in a text file, my intention was to add ', ' to every line right before the very last element 忽略使用file.readline(size)之后读取的其余行 - Ignore the rest of the line read after using file.readline(size) Python:Readline在10行后返回错误 - Python: Readline returns error after 10 lines 使用readline在python中读取文件时跳过空白行 - Skip a blank line when reading a file in python using readline
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM