Reputation: 115
I have a text file named datapolygon.txt, containing:
Polygon In [(2,0),(3,0),(3,-2),(2,-2)] [(3,0),(4,0),(4,-2),(3,-2)]
I want to assign that text value to a two dimensional list (list of lists). the result should be something like this :
polygonIn = [[(2,0),(3,0),(3,-2),(2,-2)],[(3,0),(4,0),(4,-2),(3,-2)]]is there any simple way to achieve that other than to get through some complicated loop and check every substring and index then convert it to int and make it a tuple then assign it to variable polygonIn one by one using nested loops ?
Upvotes: 1
Views: 333
Reputation: 2831
Piggy-backing on Selcuk's answer:
import ast
def processFile (filename):
theFile = open(filename, 'r')
finalList = []
for aLine in theFile:
try:
finalList.append(ast.literal_eval(aLine))
except:
useless = True
return finalList
Upvotes: 0
Reputation: 1373
Assuming you can ensure that your line is a valid list of tuples (or some other valid data type), you can use
import ast
ast.literal_eval(line)
where line
is the line you've read from your file.
If you know that you have lists of tuples and labels as you showed in your example, you could use a regular expression like ^\[([\(\-[0-9],)\s]*\]
to ensure it is one of the data lines.
Upvotes: 4
Reputation: 59184
You can use ast.literal_eval()
to convert your string to a list:
>>> import ast
>>> s = '[(2,0),(3,0),(3,-2),(2,-2)]'
>>> print(ast.literal_eval(s))
[(2, 0), (3, 0), (3, -2), (2, -2)]
and you can simply append to an empty list. Here is an example:
import ast
polygon_in = []
with open('polygon.txt', 'r') as f:
polygon_str = f.readline()
polygon_in.append(ast.literal_eval(polygon_str))
Upvotes: 4