Random space at the end of entry that generates new line in a text file python tkinter

Viewed 67

I'm working on this problem for more than 6 hours trying and testing, to figure out what the problem is.

The problem is probably for beginners but I can't find anything on internet about this problem. I made an example code here to show just the problem.

when you type something on both entries and click the button and open the text file created. you can see it did what is supposed to, but when you click again a new line is created. and at the end of the entry, you can see that there is a space and that creates a new line.

I want to remove the space at the end of entry that creates a new line. Or better explain what it causes and how can I make it better.

I hope I made the problem clear.

import tkinter as tk
from tkinter import *
import os
import subprocess

saved_data_textfile_name = "Saved data.txt"

app = tk.Tk()

font = ('Verdana', 17)

entry = tk.Entry(app, width=40, font=font)
entry2 = tk.Entry(app, width=40, font=font)

entry.pack(side="top")
entry2.pack(side="bottom")

button1 = tk.Button(app, text="save data", command=lambda: creating_file())
button1.pack(side="bottom")


def creating_file():
    saved_data = open(saved_data_textfile_name, "w+")
    data = entry.get()
    data2 = entry2.get()
    data3 = f"{data}\n{data2}"
    saved_data.truncate(0)
    saved_data.write(data3)
    print("done")
    command = '"{}" "{}" "{}"'.format(
        sys.executable,
        __file__,
        os.path.basename(__file__),
    )
    app.quit()
    subprocess.Popen(command)


def saved_data_from_relic():
    if os.path.exists(saved_data_textfile_name):
        f = open(saved_data_textfile_name)
        lines = f.readlines()
        asd = lines[0]
        asd1 = lines[1]
        entry.insert(0, asd)
        entry2.insert(0, asd1)
        f.close()


saved_data_from_relic()
app.mainloop()
1 Answers

The issue is when you are reading the content of the file in the function saved_data_from_relic, asd will contain the newline character.
One thing you can do is to read the whole content and use splitlines string method to avoid retaining newline characters.

# Change this line
lines = f.readlines()

# To
lines = f.read().splitlines()
Related