moogypoog moogypoog - 1 year ago 53
Python Question

Invalid literal for int() with base 10: ' ', reading off text file

Im trying to make a text game/rpg in python. Im getting an

line 89, in
surv = int(statload.readline(3))

ValueError: invalid literal for int() with base 10: ''

error code, when trying to read off a file. the other ones around it read fine.

Reading code-

statload = open("Statsheet.txt","r")
luck = int(statload.readline(2))
surv = int(statload.readline(3))

Code which Writes to file-

stats = open("Statsheet.txt","w")
stats.write(repr(luck)+ "\n")
stats.write(repr(surv)+ "\n")

Contents of Text File-


I have to have the "luck" and "surv" stats in "int" format, as later on in the code they are used in mathematical functions. The modules i have imported are "sys", "time", "random", and "math", if that helps at all.

Edit- will put variables into a JSON file instead, as one user suggested, and now know that the "readline" reads the bit value. thanks!

Answer Source

You are using raedline incorrectly. The argument in readline() should be number of bytes to read from the file, not the line number to read.

What you want to be doing is something like this:

with open("Statsheet.txt", "r") as file:
    stats = file.readlines()

luck = int(stats[0])
surv = int(stats[1])

But there are better options for storing stats etc than text files with each line meaning something, like SQL, json etc.