I have a text file I would like to read in that contains rows of tuples. Each tuple/row in text is in the form of ('description string', [list of integers 1], [list of integers 2]). Where the text file might look something like:
('item 1', [1,2,3,4] , [4,3,2,1])
('item 2', [ ] , [4,3,2,1])
('item 3, [1,2] , [ ])
I would like to be able to read each line in from the text file, then place them directly into a function where,
function(string, list1, list2)
I know that each line is read in as a string, but I need to extract this string some how. I have been trying to use a string.split(','), but that comes into problems when I hit the lists. Is there a way to accomplish this or will I have to modify my text files some how?
I also have a text file of a list of tuples that I would like to read in similarly that is in the form of
[(1,2),(3,4),(5,6),...]
that may contain any amount of tuples. I would like to read it in a list and do a for loop for each tuple in the list. I figure these two will use roughly the same process.
You're looking for ast.literal_eval()
.
>>> ast.literal_eval("('item 1', [1,2,3,4] , [4,3,2,1])")
('item 1', [1, 2, 3, 4], [4, 3, 2, 1])
What about using eval
?
EDIT See @Ignacio's answer using ast.literal_eval
.
>>> c = eval("('item 1', [1,2,3,4] , [4,3,2,1])")
>>> c
('item 1', [1, 2, 3, 4], [4, 3, 2, 1])
I would only recommend doing this if you are 100% sure of the contents of the file.
>>> def myFunc(myString, myList1, myList2):
... print myString, myList1, myList2
...
>>> myFunc(*eval("('item 1', [1,2,3,4] , [4,3,2,1])"))
item 1 [1, 2, 3, 4] [4, 3, 2, 1]
See @Ignacio's answer... much, much safer.
Applying the use of ast would yield:
>>> import ast
>>> def myFunc(myString, myList1, myList2):
... print myString, myList1, myList2
...
>>> myFunc(*ast.literal_eval("('item 1', [1,2,3,4] , [4,3,2,1])"))
item 1 [1, 2, 3, 4] [4, 3, 2, 1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With