I have a function which reads a file line by line and inserts it into a textinput:
def load_list(self, path, filename):
self.text_from_file.text = ''
with open(filename[0], 'r') as file:
line = file.readline()
cnt = 1
while line:
sentence = "{}".format(line.strip())
self.text_from_file.text += sentence + "\n"
line = file.readline()
cnt += 1
self.dismiss_popup()
Now file content is stored in text_from_file
variable, which is text_from_file = ObjectProperty(None)
type (I am using kivy).
What I want to do is read the text from textinput
(text_from_file.text
) and add every line into a list, so one line will be one item in the list. How can I read textinput
line by line? Does it work the same as from file? I do not want to do it right away in the function above. I want to do it later in a separate function.
An easy way to get all lines from a file into a list is like this:
with open(filename, 'r') as f:
lines = [line for line in f]
# do something with lines
EDIT:
To read a variable line by line, just split it by '\n' and iterate over the result:
for line in self.text_from_file.text.split('\n'):
print(line)