0

I am trying to read the text-file containing a list of lists containing tuples of coordinates. How do I read the file so that I would get a list of lists?

The sample content of the text file is,

[(75, 143), (187, 138)]

[(85, 140), (193, 134)]

[(65, 120)]

.

.

.

.

.

I tried to read the file using the code below. It is able to read the file. But it is storing it in 'x' as str rather than a list. How to convert it to list?

filename1 = 'testfile.txt'

m_text = open(Filename1,'r+')

m_List = []

with open(Filename1) as mf:

    x = mf.readlines()
Community
  • 1
  • 1
DJcode
  • 51
  • 1
  • 6
  • Possible duplicate of [Convert string representation of list to list](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list) – Rakesh Aug 28 '19 at 15:55
  • I am not sure if that is applicable in my case. Could you suggest a specific solution out of the solutions if you believe it exists in this link? – DJcode Aug 28 '19 at 16:12

1 Answers1

0

As per your code output comes like this, a list consist of string represented list with \n at end of each element and single \n.

['[(75, 143), (187, 138)]\n', '\n', '[(85, 140), (193, 134)]\n', '\n', '[(65, 120)]\n']

To convert that to list you need to remove thos \n from each element. and convert back to python list. This can be done using lambda,map, strip, eval functions and list comprehension which is a powerful feature of python.

filename1 = 'testfile.txt'
m_List = []
with open(file=filename1, mode='r', encoding='utf-8') as mf:
    x = mf.readlines()
    m_List = [cordinate for cordinate in list(map(lambda i: eval(str(i).strip()) if str(i).strip() else None, x)) if cordinate]
    print(m_List)

Gives output:

[[(75, 143), (187, 138)], [(85, 140), (193, 134)], [(65, 120)]]
Akash Pagar
  • 459
  • 4
  • 14