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

open method in python not let me convert string to int

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?

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

enter image description here

>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.

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