-3

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))
statload.close

Code which Writes to file-

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

Contents of Text File-

45
40

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!

moogypoog
  • 1
  • 4

3 Answers3

1

The argument to readline() is unnecessary in your case. Just drop it and the code will work:

luck = int(statload.readline())
surv = int(statload.readline())

If you're curious, statload.readline(2) reads the first two characters (45) and leaves the file pointer right before the newline that follows the 45. That newline is all that the second call to readline() reads, giving you the empty string that results in the exception you're getting.

When you omit the argument, readline() will simply read the entire line irrespective of how long it is.

Also note that you're missing parentheses after the calls to close():

statload.close()
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

It looks like once you execute luck = int(statload.readline(2)), the file pointer moves to the end of the file, and there's nothing more to read. Try this:

statload = open("Statsheet.txt","r").read().split('\n') 
luck = int(statload[0])
surv = int(statload[1])
Prateek Dewan
  • 1,587
  • 3
  • 16
  • 29
-1

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.

iScrE4m
  • 882
  • 1
  • 12
  • 31