Search code examples
pythonreadlineenumerate

Python: Understanding indexing in the use of enumerate with readline


Python code:

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:

0. Zeroth
1. First
2. Second
3. Third

The output is

1. First

Why don't I get

0. Zeroth

?


Solution

  • By the time you call myfile.readline() you have already consumed the zeroth line. (It is stored in the variable line, and the variable k holds its index 0, which is the condition you are checking).

    Then, you read another line (the "first" line) from myfile. Try printing line instead of myline.