Aozyk Aozyk - 2 months ago 6
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

readline
function doesn't help.

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

example:

v=[]
f = open("test.txt","r+",-1)
f.seek(0)
v.append(f.readline())
print(v)


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

Answer

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:
        print(row)

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

https://docs.python.org/3/library/csv.html

Comments