Read File As A List Of Tuples
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.5
Solution 1:
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
withopen('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.
Solution 2:
Yes Cyber solution is best.
For beginners
- Read file in Read mode.
- Iterate lines by
readlines()
orreadline()
- Use
split(",")
method to split line by'
- Use
float
to convertstring
value tofloat
. OR We can useeval()
also. - Use list
append()
method to append tuple to list. - Use try except to prevent code from break.
Code:
p = "/home/vivek/Desktop/test.txt"
result = []
withopen(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:passprint 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.
Solution 3:
This code should do it:
ifile=open("data/t2mG_00", "r")
lines=ifile.readlines()
data=[tuple(line.strip().split()) for line inlines]
print(data[0])
Post a Comment for "Read File As A List Of Tuples"