Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Im getting this error in python: IndexError: list index out of range

Im getting is error in python for some reason i don’t understand how these are outside of the index when there are 7 elements to the file
attack = user_stats.readlines()[2]
IndexError: list index out of range

this is the code:

with open(username + '.txt', 'r') as user_stats:
    level = user_stats.readlines()[1]
    attack = user_stats.readlines()[2]
    health = user_stats.readlines()[3]
    max_health = user_stats.readlines()[4]
    exp = user_stats.readlines()[5]
    money = user_stats.readlines()[6]

this is the txt file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

username
1
1
25
25
0
0

>Solution :

The first call to readlines() reads the full file and reaches the end of the file. Each subsequent call returns an empty string because you’ve already reached the end of the file.

There is no need to call readlines() multiple times.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading