open method in python not let me convert string to int

Advertisements

weird thing happens when I try to run this line of code:

        with open("snake score.txt", mode="r") as f:
            self.high_score = int(f.read())

it gives me:

  File "C:\Users\Lidor\PycharmProjects\100DaysOfCode\snake.py", line 77, in __init__
    self.high_score = int(f.read())
ValueError: invalid literal for int() with base 10: ''

the text inside the text is the number 0. Can someone tell me how to fix this bug?

>Solution :

Make sure you have no extra spaces in your string.

self.high_score = int(f.read().strip())

Python can’t read the file name and do stuff with the file if it has an empty whitespace/space character " " in it. Using the strip() method, you remove the whitespaces from within the code and proceed.

Leave a ReplyCancel reply