Reputation: 23
I am using this code to make labels in tkinter. After clicking on them, the text from list1 changes to text form list2. I want to append the text into the lists from a txt file.
self.list1 = [line.rstrip('\n') for line in open("file.txt", encoding = "utf-8")]
self.list2 = [line.rstrip('\n') for line in open("file2.txt", encoding = "utf-8")]
Do I have to make for each list a single txt file? (How) can I make several lists from just one file?
Thanks
Upvotes: 1
Views: 154
Reputation: 515
def from_file_to_lists(name,lists): #Where lists[0] = list1, lists[1] = list2 etc
i = 0
for line in open(name, encoding = "utf-8"):
line = line.rstrip('\n')
if "line%s" % (i+1) in line: #if next list in line
i +=1 #go to next list
continue #dont write list name inside the list
lists[i].append(line)
return lists
#How to call
list0 = []
list1 = []
list2 = []
lists = [list0,list1,list2]
lists = from_file_to_lists("file.txt",lists)
Your file.txt should be like
Hello i
am list0
list1
Hello, i am
the second list
list2
i am the last
Your list numbering inside the txt file should start from 0, else change
if "line%s" % (i+1) in line:
to
if "line%s" % (i+2) in line:
Upvotes: 2