Reputation: 25
I run this code in the Python IDLE, and it will only return the amount of letters specified instead of the line specified.
if os.path.exists(saveDir + name + '.txt') == True:
print('welcome back ' + name + '.')
file = open(saveDir + name + '.txt')
race = file.readline(1)
else:
race = intro()
When I print the race variable, it comes out as the G (The input name is Grant). The text file looks like this
Grant
Human
What Am I doing wrong?
Upvotes: 0
Views: 215
Reputation: 234
if os.path.exists(saveDir + name + '.txt') == True:
print('welcome back ' + name + '.')
file = open(saveDir + name + '.txt')
race = file.readline() # this reads one line at a time
raceType = file.readline() # this will give you the second line (human)
else:
race = intro()
Upvotes: 0
Reputation: 852
race = file.readline(1)
returns 1 byte (character) of the line (see here). You want to return the entire line so call race = file.readline()
.
Upvotes: 1
Reputation: 1051
Are you trying to read a single line, or all the lines? file.readline()
will return the first line of the file as a string. If called again, it will return the second line, and so on. You can also load all the lines of the file as a list with file.readlines()
, and then get the first or second element by using [0]
or [1]
, so file.readlines()[1]
will yield "Human".
Upvotes: 0