Read file as a list of tuples

I want to read a text file using Python. My list should be like this:

mylist = [(-34.968398, -6.487265), (-34.969448, -6.488250),
          (-34.967364, -6.492370), (-34.965735, -6.582322)]

My text file is:

-34.968398,-6.487265
-34.969448,-6.488250
-34.967364,-6.492370
-34.965735,-6.582322

My Python code is:

f = open('t3.txt', 'r')
l = f.readlines()
print l

My results:

['-34.968398 -6.487265\n', '-34.969448 -6.488250\n', 
 '-34.967364 -6.492370\n', '-34.965735 -6.582322\n']
+4
source share
2 answers

One of the most effective ways to read delimited data like this is numpy.genfromtxt. for instance

>>> import numpy as np
>>> np.genfromtxt(r't3.txt', delimiter=',')
array([[-34.968398,  -6.487265],
       [-34.969448,  -6.48825 ],
       [-34.967364,  -6.49237 ],
       [-34.965735,  -6.582322]])

Otherwise, you can use list comprehension to read line by line, divide by ',', convert values ​​to, floatand finally create a listtuple

with open('t3.txt') as f:
    mylist = [tuple(map(float, i.split(','))) for i in f]

Please note that when you open the file with with, it will take care of closing after that, so you do not need to.

+11
source

Yes. It’s best to use a cyber solution.

  • .
  • readlines() readline()
  • split(",") '
  • float string float. eval().
  • append() .
  • , , .

:

p = "/home/vivek/Desktop/test.txt"
result = []
with open(p, "rb") as fp:
    for i in fp.readlines():
        tmp = i.split(",")
        try:
            result.append((float(tmp[0]), float(tmp[1])))
            #result.append((eval(tmp[0]), eval(tmp[1])))
        except:pass

print result

:

$ python test.py 
[(-34.968398, -6.487265), (-34.969448, -6.48825), (-34.967364, -6.49237), (-34.965735, -6.582322)]

. readline() .

+4

All Articles