Python 以元组列表的形式读取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28090960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read file as a list of tuples
提问by marcelorodrigues
I want to read a text file using Python. My list must be like this:
我想使用 Python 读取文本文件。我的清单必须是这样的:
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:
我的 Python 代码:
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']
采纳答案by Cory Kramer
One of the most efficient way to read delimited data like this is using numpy.genfromtxt
. For example
像这样读取分隔数据的最有效方法之一是使用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]])
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
否则,您可以使用列表理解逐行读取、拆分','
、将值转换为float
,最后生成一个列表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.
请注意,当您使用with
它打开文件时,它会在之后自行关闭,因此您不必这样做。
回答by Vivek Sable
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.
- 以读取模式读取文件。
- 通过
readlines()
或迭代行readline()
- 使用
split(",")
方法来分割线'
- 使用
float
转换string
价值float
。OR 我们也可以使用eval()
。 - 使用 list
append()
方法将元组附加到列表。 - 使用 try except 来防止代码中断。
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.
注意:readline()从文件中读取一行。
回答by user9785405
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])