1 list every line 1 key every word | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

1 list every line 1 key every word

Hi there. I would like to know if this could be possible. File.txt Word1, word2 Word3, word4 From that file i want to create: List1 = [word1, word2] List2 = [Word3, word4] The first part of my program write data input on a file. The second one read these data and store them into list, on line by list, 1 word or sentence separated by comma by key list. Its useful because when the program is closed all variables are reseted. Thats my way to have a kind of savestate. Thank you for your help.

23rd Dec 2016, 11:07 PM
Flynn
Flynn - avatar
4 Answers
+ 3
use open() method let's say your file is called state.txt f = open('state.txt', 'r') # open state.txt in read mode lst = f.read().split(' ') # read the file and split by spaces this will create a list of words from the file which were seperated by a space as delimiter from there create a list of pairs: pairs = [lst[x:x+2] for x in range(0, len(lst), 2)]
23rd Dec 2016, 11:56 PM
Burey
Burey - avatar
+ 2
Yes, it's possible... Not necessarly the most adequat, but it works: maybe more accurate to use sqlite? And if you target python on android ( it may be lists made me thinking to it ), there are built-in kind of cookies...
23rd Dec 2016, 11:52 PM
visph
visph - avatar
0
''' Create a plain text file in the directory you have your code stored. In the example case called mytext.txt with your data written on seperate lines word1,word2 word3,word4 Look at python's https://docs.python.org/3/tutorial/inputoutput.html Reading and Writing Files There are many options, if you want to experiment ''' my_data = [] with open('mytext.txt','r+') as my_file: for line in my_file: # removes new line characters new_line = line.strip() # converts plain text to list my_data.append(new_line.split(',')) # Assign to names as you desire line1 = my_data[0] line2 = my_data[1] print(line1) print(line2)
24th Dec 2016, 12:26 AM
richard
0
Happy Christmas! I would like to thank you for you help. Richard your solution did the job with a little modification. Here is the code. temp.txt: word1,word 2 word 3,word4 word 5,word 6 list1 = [] i = 1 with open('temp.txt','r+') as my_file: for line in my_file: # removes new line characters new_line = line.strip() # converts plain text to list locals()["list"+str(i)] = new_line.split(',') i += 1 print(list1[0]) = word1 print(list1[1]) = word 2 print(list2[0]) = word 3 print(list2[1]) = word4 print(list3[0]) = word 5 print(list3[1]) = word 6 This is perfect! Thank you again Hope this can help others coding dudes !
25th Dec 2016, 6:48 PM
Flynn
Flynn - avatar