Search code examples
pythonbackspacereadlines

How to readlines without having the \n at the end? (python)


As I was finishing off a game I made, I made a save button that saves to a file. When the game opens, it will then read the file and save those lines as variables. I do so, but then I see that it needs to be an integer, so I use int(). But then it does not work, because the variable is "0\n" instead of "0". I have checked many other questions, but they do not ask or answer the same question.

So I am wondering, is there a way to readlines() without the \n at the end? Or is there a way that I can backspace the variable automatically? Here is my code:

import tkinter as tk
from PIL import Image, ImageTk

# --- functions ---
def eggvalue_change():
    global eggvalue, eggvalueupgrade, money, eggz
    if money > int(round(eggvalueupgrade)):
        eggz -= eggvalueupgrade / eggvalue
        eggvalue+=0.2
        eggvalueupgrade += int(round(eggvalueupgrade + (eggvalueupgrade / 7)))
def moar_eggz():
    global eggzps, chookz
    chookz += 1
def saving():
    savedfile.write(money)
    savedfile.write(eggvalueupgrade)
    savedfile.write(eggzps)
    savedfile.write(chookz)
    savedfile.write(eggvalue)
    savedfile.write(eggz)
def main_loop():
    global eggz, eggzps, money
    eggzps = chookz / 100.0
    money = eggz * eggvalue

    try:
        openbutton2.config( text="Egg Value: " + str(eggvalue) + " --> " + str(eggvalue+0.2) + " ($" + str(eggvalueupgrade) + ")", command=eggvalue_change)
        label2.config(text="Money: $" + str(int(round(money))), font=("Terminal", 50), borderwidth=5, relief="ridge", bg="black", foreground="white",pady=10, padx=498)
        if eggzps >= 10:
            label1.config(text="| Chickens: " + str(chookz)+" | Eggs: " + str(int(round(eggz)))+" | Eggs Per Second: " + str(int(round(eggzps)))+" | Egg Value: $" + str(eggvalue) + " |", font=("Terminal", 20), borderwidth=4, relief="ridge", bg="black", foreground="red",pady=10, padx=498)
        elif eggzps < 10:
            label1.config(text="| Chickens: " + str(chookz)+" | Eggs: " + str(int(round(eggz)))+" | Eggs Per Second: " + str(eggzps)+" | Egg Value: $" + str(eggvalue)+ " |", font=("Terminal", 20), borderwidth=4, relief="ridge", bg="black", foreground="red",pady=10, padx=498)
        if money < int(round(eggvalueupgrade)):
            openbutton2.config(fg="gray")
        elif money > int(round(eggvalueupgrade)):
            openbutton2.config(fg="white")
    except Exception as e: 
        print(e) # display exception to see problem
    root.after(20, main_loop)
def update_eggz():
    global eggz
    try:
        eggz += eggzps
    except Exception as e:
        print(e) # display exception to see problem

    # repeat it after 1000ms
    root.after(1000, update_eggz)

# --- main ---

root = tk.Tk()
root.title("Chicken Clicker")

savedfile = open("savedata\\mainsave.txt", "a+")
savedlines = savedfile.readlines()
print savedlines


if savedlines == []:
    eggz = 0
    eggvalue = 0.2
    chookz = 0
    eggzps = 0.0
    eggvalueupgrade = 100
    money = eggz * eggvalue

eggz = int(savedlines[0])
eggvalue = int(savedlines[1])
chookz = int(savedlines[2])
eggzps = int(savedlines[3])
eggvalueupgrade = int(savedlines[4])
money = int(savedlines[5])

savedfile.close()

# empty labels - `update_labels` will add text  

label2 = tk.Label(root)
label1 = tk.Label(root)

label2.pack()
label1.pack()

chickencnv = Image.open("img\\1.png")
chicken = ImageTk.PhotoImage(chickencnv)
openbutton3 =tk.Button(root, bg="black", fg="white", font=("Terminal", 13), command=saving)
openbutton2= tk.Button(root, bg="black", fg="gray", font=("Terminal", 15))
openbutton1= tk.Button(root, image=chicken, width=500, height=500, command=moar_eggz, bg="black")

openbutton1.pack()
openbutton2.pack()
openbutton3.pack()


# run it first time at once
update_eggz()
main_loop()


root.mainloop()

If there is no answer, I am fine with you commenting or answering that.


Solution

  • First of all, your code have logical bug.

    if savedlines == []:
        eggz = 0
        eggvalue = 0.2
        chookz = 0
        eggzps = 0.0
        eggvalueupgrade = 100
        money = eggz * eggvalue
    
    eggz = int(savedlines[0])
    eggvalue = int(savedlines[1])
    chookz = int(savedlines[2])
    eggzps = int(savedlines[3])
    eggvalueupgrade = int(savedlines[4])
    money = int(savedlines[5])
    

    You check wheter savedlines is empty list and set some values accordingly. But, if this is true, following lines will fail with IndexError, since your list is empty. You need to change this to:

    if savedlines == []:
        eggz = 0
        eggvalue = 0.2
        chookz = 0
        eggzps = 0.0
        eggvalueupgrade = 100
        money = eggz * eggvalue
    else:
        eggz = int(savedlines[0])
        eggvalue = int(savedlines[1])
        chookz = int(savedlines[2])
        eggzps = int(savedlines[3])
        eggvalueupgrade = int(savedlines[4])
        money = int(savedlines[5])
    

    Now, to address the question. After the line:

    savedlines = savedfile.readlines()
    

    You should add following line which will strip \n from the end of the lines:

    savedlines = [line.rstrip("\n") for line in savedlines]