[英]Python: Understanding indexing in the use of enumerate with readline
Python code: Python 代码:
myfile = open("test-file.csv", "r")
for k, line in enumerate(myfile,0):
if k == 0:
myline = myfile.readline()
print(myline)
break
myfile.close()
and test-file.csv is:和 test-file.csv 是:
0. Zeroth
1. First
2. Second
3. Third
The output is output 是
1. First
Why don't I get为什么我得不到
0. Zeroth
? ?
By the time you call myfile.readline()
you have already consumed the zeroth line.当您调用
myfile.readline()
时,您已经使用了第零行。 (It is stored in the variable line
, and the variable k
holds its index 0, which is the condition you are checking). (它存储在变量
line
中,变量k
保存其索引 0,这是您正在检查的条件)。
Then, you read another line (the "first" line) from myfile
.然后,您从
myfile
读取另一行(“第一行”)。 Try printing line
instead of myline
.尝试打印
line
而不是myline
。
Because "zeroth" has already been read in the loop,因为循环中已经读取了“第零”,
myfile = open("test-file.csv", "r")
for k, line in enumerate(myfile,0):
if k == 0:
print(line) # this should output "zeroth"
myline = myfile.readline() #this will read "First"
print(myline)
break
myfile.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.