Im new to Python and trying to do some code on my own. I’d like to take input from a .txt file and then store each line of that .txt into a different list.
For example, if the file has 2 lines, I want to do something like this:
.txt file:
blue, red, yellow, orange city, car, airplane, dinosaur
python output:
list1 = [blue, red, yellow, orange] list2 = [city, car, airplane, dinosaur]
I tried working with loops for extracting the content in form of lists, but I dont know how to store the actual results from the loop into different lists. I’m currently using the open() function to work with the files, but can’t figure how to achieve this.
Thanks!
EDIT1: 23 Jun 2021
This is the work I’m using.
with open('file.txt') as fh: for line in fh: print(line.split("n"))
This code prints in the console 2 lists (because the file has 2 lines). But I dont know how to store those lists in 2 differentes variables.
Advertisement
Answer
First you need to open the file as read mode. You can handle it. A little help for you.
If we imagine you have a lot of lines to take. You can use a loop to get all the lines step by step(You can get all lines as an array and then get them in loop or take one line in every step – I’m letting you to find this functions) and in every step you can use another loop inside of it and take the strings. To do that you should use split for every line and get array of strings belongs that line. Split functions takes a string as a parameter and returns you an array that includes all that strings. You can check it.
But in your situation you want to create new array for every line in your example for 2 lines, you can take first line from file and split it and after that you can do this for other too. So you will get to 2 array includes lines.
But if you wonder how can i do this for uncertain number of line, you can use the first method that I mentioned and add all line arrays to an array at the end of every step in your first(inclusive) loop . So you will have all arrays that includes all line’s string in an array. You can think like your first index of array will be your first line strings.
To imagine the figure you will get
all_lines=[ [blue, red, yellow, orange], [city, car, airplane, dinosaur], [one,two,three,four] ]
or something like that.