A question about 'readlines' and 'split()'

Question:

For a file contains two strings: True and 26. When I use readlines to get those strings:

a, b = file.readlines()[1].split()
print(a, b)
# True 26

the result is two strings: True and 26. However, when I just want to get the string ’26’ and added another line after them:

a, b = file.readlines()[1].split()
print(a, b)
# True 26
c = file.readlines()[1].split()[1]
# IndexError: list index out of range

a index error occurs. I do not understand why this happens.

The result should be 26, so how to debug that?

Asked By: Bigskydog

||

Answers:

I’m assuming you are using Python.

When you use readlines multiple times it countinues reading from where it last stopped. When you run the line two times you will receive an empty array the second time and thus IndexError on file.readlines()[1]. Either open the file for reading again or keep the value the first time.

Answered By: Anton
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.