-3

I am trying to save some variables to a file on separate lines.

My code looks like this:

def saveall(sname, senemyname, scheckpoint,):
    file = open("savefile.sav", "w")
    file.writelines([sname, senemyname, scheckpoint])
    file.close()

If I put saveall("John","Steve","Crossroads") in my code, I want it to make a file called savefile.sav, containing:

John

Steve

Crossroads

However, when I run the program, savefile.sav contains:

JohnSteveCrossroads

What am I doing wrong?

Austin
  • 25,759
  • 4
  • 25
  • 48
DPS2004
  • 1
  • 2
  • 1
    Some things to remember in Python: readlines() doesn't strip the newline char, while writelines() doesn't append the newline char – Chris Clayton Feb 27 '19 at 17:40

2 Answers2

3

writelines expects each string to be newline terminated. So you need:

file.writelines([sname + '\n', senemyname + '\n', scheckpoint + '\n'])

From the python docs:

writelines(lines)

Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.

But usually it's more idiomatic to do file.write('\n'.join([sname, senemyname, scheckpoint)). Note that that doesn't add the file newline.

You should also be using contexts for files, because if an exception is raised you may not close your file:

with open('savefile.sav', 'w') as f:
    f.write('\n'.join([sname, senemyname, scheckpoint]))
Bailey Parker
  • 15,599
  • 5
  • 53
  • 91
1

writelines doesn't add separators between the lines, so you have to add them yourself:

def saveall(sname, senemyname, scheckpoint,):
    file = open("savefile.sav", "w")
    file.writelines((line + '\n' for line in [sname, senemyname, scheckpoint]))
    file.close()

saveall("John","Steve","Crossroads")

File content:

John 
Steve 
Crossroads
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50