MiruMiruKun MiruMiruKun - 5 months ago 34
Python Question

How to convert a string with a few values in a file to a list? [resolved]

I'm trying to do a program which would read the lines from a file, with lists-shaped sentences on each line. Each line would present like this:

['First Sentence','Second Sentence','Answer 1',Line number,'Answer 2',Line number]

each of these elements in the list must be in a list, which would present like this:

menuList=['First Sentence','Second Sentence','Answer 1',Line number,'Answer 2', Line number]

I tried to do it by just doing this:

the file, named test.txt:

['Sentence 1','Sentence 2','Answer 1',2,'Answer 2',3]

the code:

from linecache import getline

But the list I was supposed to obtain became this:

['[',"'",'S','e','n','t','e','n','c','e',' ','1',"'",',',"'",'S','e','n','t','e','n','c','e',' ','2',"'",',',"'",'A','n','s','w','e','r',' ','1',"'",',','2',',',"'",'A','n','s','w','e','r',' ','2',"'",',','3',']']

If you don't understand this mess, the program basically stored each character of the line and stored them in the 'content' list.

So, do someone know how could I store the list as it was supposed to be stored? I can review the way to write things into the txt file, it's not a problem. But I need to have 6 parts in my lists, with the first part and second part of the sentence, the two answers, and the linked sentence where they lead to.

It is supposed, after cleaning everything, printing this:

Sentence 1
Sentence 2

→ Answer 1
→ Answer 2

Which do you choose?

And the player choose one of the answers, linked to a value, which is the next line to read.

Answer Source

The given string is a python literal; you can use ast.literal_eval to convert the string to python object:

>>> ast.literal_eval("['Sentence 1','Sentence 2','Answer 1',2,'Answer 2',3]")
['Sentence 1', 'Sentence 2', 'Answer 1', 2, 'Answer 2', 3]

import ast
from linecache import getline

content = ast.literal_eval(getline(test.txt, 1))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download