1

I have a file that contains a list of numbers in a format exactly how Python would print it. It is a complex list and in the file it looks like this:

([(515.51, 615.76), (42.28, 152.3), (223.29, 138.07)], 1)
([(382.27, 502.27), (323.54, 473.01), (212.32, 433.57)], 2)
([(188.74, 442.8), (245.7, 461.47), (391.02, 508.96)], 3) 

I would like to know how to get it from the file and generate exactly the same list as numbers in Python.

tzoukritzou
  • 277
  • 1
  • 2
  • 13

1 Answers1

0

Try the below code. I am assuming that I have the given data items in this question in a file called data.txt.

data.txt

([(515.51, 615.76), (42.28, 152.3), (223.29, 138.07)], 1)
([(382.27, 502.27), (323.54, 473.01), (212.32, 433.57)], 2)
([(188.74, 442.8), (245.7, 461.47), (391.02, 508.96)], 3) 

data.py

lists = [];
integers = []

with open("data.txt") as f:
    for line in f.readlines():
        # Each line of file is a tuple with 2 items, first one is list, second one in an integer
        tuple = eval(line.strip());

        # Append each list from each line to lists list
        lists.append(tuple[0]);

        # Append each integer from each line to integers list
        integers.append(tuple[1]);

print(lists);
print(integers);

Reference: Converting a string representation of a list into an actual list object

hygull
  • 7,072
  • 2
  • 35
  • 42