[英]readline with for loop issue
I have a .txt file with 10 sort lines of text (three comma separated words each), but the following only reads four of the lines in the text file: 我有一个.txt文件,其中包含10行文本排序(每行三个逗号分隔的单词),但是以下内容仅读取文本文件中的四行:
def main():
path = '/path/to/file.txt'
f = open(path, 'r')
for line in f:
s = f.readline()
print(s)
f.close
main()
but this will read all the lines but into a list: 但这会将所有行读入一个列表中:
def main():
path = '/path/to/file.txt'
f = open(path, 'r')
s = f.readlines()
print(s)
f.close
main()
Why doesn't the for loop work? 为什么for循环不起作用?
When using for line in f
you're already reading a line. for line in f
您已经在读取一行。 So it's useless to do readline()
since it will read the next line which explains why you get 4 lines read instead of 10. 因此,执行
readline()
毫无用处,因为它将读取下一行,这解释了为什么读取4行而不是10行。
When you open your file.txt, you got an _io.TextIOWrapper
object as f. 当您打开file.txt时,您将获得一个
_io.TextIOWrapper
对象作为f。
for line in f:
will iterate on the f
iterator to yield each line of your file successively,line by line, into your line
variable. for line in f:
将迭代的f
迭代器线以获得你的文件的每一行先后,线,进入你的line
变量。 You can see how iterators work here . 您可以在此处查看迭代器的工作方式。
When the f
iterator moves one line after the start of your loop, you read another line with your s = f.readline()
and that moves your iterator one more line ahead. 当
f
迭代你的循环开始后移动一行,你看了另一条线与s = f.readline()
和提前移动你的迭代下一行。 When you end your first loop, another line of f is read with your for line in f:
then, you skip that line by reading the next line with s = f.readline()
. 当您结束第一个循环时,将
for line in f:
的for line in f:
读取f的另一行for line in f:
然后,通过读取s = f.readline()
的下一行来跳过该行。
Your code will work with 您的代码将与
def main():
path = '/path/to/file.txt'
with open(path, 'r') as f:
for line in f:
print(line)
main()
This would work to get all the lines: 这将使所有行起作用:
with open('/path/to/file.txt') as fp:
for line in fp.read().split('/n'):
print(line)
for line in f:
is already iterating over the lines in the file, you are then attempting to read
a line within that iteration. for line in f:
中的行,已经在文件中的行上进行了迭代,然后您尝试在该迭代中read
一行。 Just use the value of line
and forget about s
只需使用
line
的值而忽略s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.