How do I specify which line to read using readline()?

I think it is possible to write readline(4) to read line 4 in the file. But when I do it, it doesn’t work. Here’s my code and I only get “Invalid save file” in the system console. (That means it didn’t find the header). It works if I leave the () empty.

loadFile = open(“MyFile.sav”, “r”)
header = loadFile.readline(1)
header = header[0:-1]
if header == “This is a valid save file”:
own[‘Block’] = str(loadFile.readline(2))[0:-1]
own[‘xcor’] = int(loadFile.readline(3))
own[‘ycor’] = int(loadFile.readline(4))
own[‘zcor’] = int(loadFile.readline(5))
nextline = str(loadFile.readline(6))[0:-1]
else:
print(“Invalid save file”)

And here is the save file:

This is valid save file
TestBlock
5
5
5

readline() returns the next line of text. To better understand this, you have to understand that when reading a file in Python, Python keeps track of where in the file you currently are. So, a method like readline() reads the next line starting at this position, and then advances you to past the end of that line. To do what you want, think you just want to empty the file into a list:


with open('MyFile.sav', 'r') as f:
    save_data = f.read().split()  # Read the contents of the file and split it along newlines

header = save_data[0]
own['Block'] = save_data[2]
# etc

You could also look into JSON, which Python has fantastic support for.

Thanks alot for the quick answer, I will check out JSON and hopefully that’ll work :slight_smile:

For proper cross-platform newline support, you should be using “rU”

with open('MyFile.sav', 'rU') as f:
    save_data = f.read().split()  # Read the contents of the file and split it along newlines

etc...