我想用Python读取文本文件.我的清单必须是这样的:
mylist = [(-34.968398, -6.487265), (-34.969448, -6.488250),
(-34.967364, -6.492370), (-34.965735, -6.582322)]
Run Code Online (Sandbox Code Playgroud)
我的文本文件是:
-34.968398,-6.487265
-34.969448,-6.488250
-34.967364,-6.492370
-34.965735,-6.582322
Run Code Online (Sandbox Code Playgroud)
我的Python代码:
f = open('t3.txt', 'r')
l = f.readlines()
print l
Run Code Online (Sandbox Code Playgroud)
我的结果:
['-34.968398 -6.487265\n', '-34.969448 -6.488250\n',
'-34.967364 -6.492370\n', '-34.965735 -6.582322\n']
Run Code Online (Sandbox Code Playgroud)
Cor*_*mer 15
读取这样的分隔数据的最有效方法之一就是使用numpy.genfromtxt.例如
>>> 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]])
Run Code Online (Sandbox Code Playgroud)
否则,您可以使用列表推导逐行读取,拆分',',转换值float,最后生成列表tuple
with open('t3.txt') as f:
mylist = [tuple(map(float, i.split(','))) for i in f]
Run Code Online (Sandbox Code Playgroud)
请注意,当您使用with它打开文件时,将关注自己之后关闭,因此您不必这样做.
是的Cyber解决方案是最好的.
对于初学者
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
Run Code Online (Sandbox Code Playgroud)
输出:
$ python test.py
[(-34.968398, -6.487265), (-34.969448, -6.48825), (-34.967364, -6.49237), (-34.965735, -6.582322)]
Run Code Online (Sandbox Code Playgroud)
注意:readline()从文件中读取一行.
| 归档时间: |
|
| 查看次数: |
28639 次 |
| 最近记录: |