Reputation: 91
I have the python file with a list in it.
localhost tmp]$ cat 1.txt
['aaaaaaa','bbbbbbb','cccccc','dddddddd']
I want to read each element of the list. I am getting each character instead. I can read each value of the list if it is declared as list variable, but my list is in the text file.
#!/usr/bin/python
def get_vminfo(vms):
for vm in vms:
print vm
#vms=['aaaaaaa','bbbbbbb','cccccc','dddddddd']
with open('1.txt','r') as input:
vms=input.read()
get_vminfo(vms)
How do I print each list value ???
Upvotes: 0
Views: 171
Reputation: 542
This works for smaller files. Keep in mind that the data is stored in your computer's memory, as it build an array of data, so if you're dealing with big files, better thing about using iterators instead this approach.
Sadly, in iterators, you can't access the data already read.
Upvotes: 0
Reputation: 369414
Using ast.literal_eval
:
>>> import ast
>>> with open('1.txt') as f:
... ast.literal_eval(f.read())
...
['aaaaaaa', 'bbbbbbb', 'cccccc', 'dddddddd']
>>> with open('1.txt') as f:
... for x in ast.literal_eval(f.read()):
... print x
...
aaaaaaa
bbbbbbb
cccccc
dddddddd
Upvotes: 1