Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file as a list of tuples

Tags:

python

I want to read a text file using Python. My list must 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:

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']
like image 820
marcelorodrigues Avatar asked Jan 22 '15 14:01

marcelorodrigues


People also ask

Can we convert tuples into list?

Python list method list() takes sequence types and converts them to lists. This is used to convert a given tuple into list. Note − Tuple are very similar to lists with only difference that element values of a tuple can not be changed and tuple elements are put between parentheses instead of square bracket.

How do you convert a string to a list of tuples?

When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.


3 Answers

One of the most efficient way to read delimited data like this is using numpy.genfromtxt. For example

>>> 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 could use a list comprehension to read line by line, split on ',', convert the values to float, and finally produce a list of tuple

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

Note that when you open a file using with it will take care of closing itself afterwards so you don't have to.

like image 192
Cory Kramer Avatar answered Oct 22 '22 03:10

Cory Kramer


Yes Cyber solution is best.

For beginners

  1. Read file in Read mode.
  2. Iterate lines by readlines() or readline()
  3. Use split(",") method to split line by '
  4. Use float to convert string value to float. OR We can use eval() also.
  5. Use list append() method to append tuple to list.
  6. Use try except to prevent code from break.

Code:

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

Output:

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

Note: A readline() reads a single line from the file.

like image 6
Vivek Sable Avatar answered Oct 22 '22 04:10

Vivek Sable


This code should do it:

ifile=open("data/t2mG_00", "r")
lines=ifile.readlines()
data=[tuple(line.strip().split()) for line in lines]
print(data[0])
like image 1
user9785405 Avatar answered Oct 22 '22 03:10

user9785405