Reading in a tuple of lists from a text file as a tuple, not a string - Python

I have a text file that I would like to read containing strings of tuples. Each tuple / line in the text is in the form ("description line", [list of integers 1], [list of integers 2]). Where the text file might look something like this:

('paragraph 1', [1,2,3,4], [4,3,2,1])
("paragraph 2", [], [4,3,2,1])
('clause 3, [1,2], [])

I would like to be able to read each line from a text file and then put them directly in a function where

function(string, list1, list2) 

I know that each line is read as a line, but I need to somehow extract this line. I am trying to use string.split (','), but this causes problems when getting into lists. Is there a way to accomplish this or will I have to somehow modify my text files?

I also have a tuple list text file that I would like to read similarly, which is in the form

[(1,2), (3,4), (5,6), ...]

which can contain any number of tuples. I would like to read it in a list and make a for loop for each tuple in the list. I believe that these two will use roughly the same process.

+7
source share
3 answers

How about using eval ?

EDIT See @Ignacio answer with 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 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.

Using ast will give:

 >>> 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] 
+12
source

You are 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]) 
+21
source

You can also look at the pickle module to save python objects to text files and then read them again.

+1
source

All Articles