2

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

Aozyk
  • 33
  • 5
  • 2
    Please show a [mcve] of what it is you are exactly trying to solve. Show a sample input you are sending to your code, and what the expected output should be. Show what is currently happening that should not be happening. – idjaw Sep 11 '16 at 01:31
  • added example code for demonstration purposes. – Aozyk Sep 11 '16 at 01:50
  • 2
    Possible duplicate of [Reading rows from a CSV file in Python](http://stackoverflow.com/questions/13428318/reading-rows-from-a-csv-file-in-python) – gabra Sep 11 '16 at 02:13
  • I had no idea about CSV when i made this question. – Aozyk Sep 11 '16 at 02:46

2 Answers2

1

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

JustDanyul
  • 13,813
  • 7
  • 53
  • 71
  • 2
    hey this works, altough, would this csv apply for another separation method? like `:` `;` ? – Aozyk Sep 11 '16 at 02:02
  • sure, just pop in the delimiter you want in the reader function, for example csv.reader(csvfile, delimiter=':') to use : as a seperator – JustDanyul Sep 11 '16 at 02:04
  • after further testing and reading, i'm interested in how do i select 1 single row? or shouls i transform the `print(row)` into `v.append(row)` and thus select the desired list using `v[0]` – Aozyk Sep 11 '16 at 02:16
1

To me, it looks like you're trying to read a file, and split it by ,.
This can be accomplished by

f = open("test.txt", "r+").read()
v = f.split(",")
print(v)

It should output

['cat', ' dog', ' dinosaur', ' elephant\ncheese', ...]

And so forth.

baranskistad
  • 2,176
  • 1
  • 21
  • 42