I have a problem with saving and reading a file in a kivy application. For some reason new spaces appear after saving the file.
I think the point is that “text at the end with \n” is read as one line, but is entered into the field as two lines, and then saved to a file as 2 lines, and this becomes a problem.
I signed where in the code the work with the file occurs. Please help me because I don't understand it myself.
test.py '''
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
class Screeen(Screen):
None
class Manager(ScreenManager):
None
class appApp(App):
def on_start(self): # When the application starts, the file is read and the data is entered into the input fields
with open("settings.txt", 'r') as f:
self.a = f.readline()
self.b = f.readline()
self.c = f.readline()
f.close()
self.sm.get_screen("Screeen").ids.a.text = self.a
self.sm.get_screen("Screeen").ids.b.text = self.b
self.sm.get_screen("Screeen").ids.c.text = self.c
def on_stop(self): # after exiting the application, data from the input fields is saved to a file
with open("settings.txt", "w") as f:
f.write(self.sm.get_screen("Screeen").ids.a.text + "\n")
f.write(self.sm.get_screen("Screeen").ids.b.text + "\n")
f.write(self.sm.get_screen("Screeen").ids.c.text + "\n")
def __init__(self, **kwargs):
super().__init__(**kwargs)
# type-hint will help the IDE guide you to methods, etc.
self.sm: ScreenManager = Builder.load_file("test.kv")
def build(self):
return self.sm
if __name__ == "__main__":
appApp().run()
'''
test.kv:
'''
Manager:
Screeen:
<Screeen>:
name: "Screeen"
FloatLayout:
size: root.width, root.height
TextInput:
id: a
text: ""
size_hint: (.25, .1)
pos: root.width * 1 / 3 , root.height * 3 / 4
TextInput:
id: b
text: ""
size_hint: (.25, .1)
pos: root.width * 1 / 3 , root.height * 2 / 4
TextInput:
id: c
text: ""
size_hint: (.25, .1)
pos: root.width * 1 / 3 , root.height * 1 / 4
'''
and settings.txt is empty
readline() will return the terminating newline. Therefore, you could rewrite the on_start() function as follows:
def on_start(self):
_ids = self.sm.get_screen("Screeen").ids
with open("settings.txt") as f:
for attr in "abc":
_ids[attr].text = f.readline().rstrip()