-1

I need to save some variables to a file and load them in, I save each variable to a new line so i use "\n", however when i have to convert it back to an integer when I read from the file i get an error because \n counts as a string. How do i write variables in a new line and read them as integers too?

x=0
y=0

def save_to_file():
    file = open("savefile.txt","a")
    file.write('%s\n' % x)
    file.write('%s\n' % y)
    file.close()

def load_from_file():
    file = open("savefile.txt","r")
    x=int(file.readline())
    y=int(file.readline())
    file.close()
  • 2
    `int(file.readline().strip())` – Selcuk Nov 05 '20 at 07:29
  • 2
    Does this answer your question? [How can I remove a trailing newline?](https://stackoverflow.com/questions/275018/how-can-i-remove-a-trailing-newline) – funie200 Nov 05 '20 at 07:30
  • You should do something like x=file.realine( ) and x=int(x.strip(‘\n’) ) – prathap sagar Nov 05 '20 at 07:32
  • You shouldn't get an error. `int('42\n')` works fine. To cite the documentation: "the literal can be preceded by `+` or `-` (with no space in between) and surrounded by whitespace" – Matthias Nov 05 '20 at 09:06

2 Answers2

0

You can use rstrip("") to remove any character from a string

x=0
y=0

def save_to_file():
    file = open("savefile.txt","a")
    file.write('%s\n' % x)
    file.write('%s\n' % y)
    file.close()

def load_from_file():
    file = open("savefile.txt","r")
    x=int(file.readline().rstrip("\n"))
    y=int(file.readline().rstrip("\n"))
    file.close()
Josh
  • 23
  • 6
0

Use the .strip() method to remove all leading and trailing whitespace from a string. Here's a link to a W3 schools article that explains in more depth: https://www.w3schools.com/python/ref_string_strip.asp

In your case, it would be something like this: x=int( file.readline().strip() )

Jack H.
  • 115
  • 10