Aozyk Aozyk - 4 months ago 12
Python Question

How to use lists from a text file in python?

i have been trying to read/write values(lists) in a .txt file and using them later, but i can't find a function or something to help me use these values as lists and not strings, since using the

function doesn't help.

Also, im don't want to use multiple text files to make up 1 list


f = open("test.txt","r+",-1)

in test.txt

cat, dog, dinosaur, elephant
cheese, hotdog, pizza, sushi
101, 23, 58, 23

im expecting to the list
v = [cat, dog, dinosaur, elephant]
in separate indexes, but by doing this code (which is totally wrong) i get this instead
v = ['cat,dog,dinosaur,elephant']
which is what i don't want


Sounds like you want to read it as comma separated values.

Try the following

import csv
with open('test.txt', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:

I believe that will put you on the right track. For more information about how the csv parser works, have a look at the docs