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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:43:53  来源:igfitidea点击:

Read file as a list of tuples

python

提问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 withit will take care of closing itself afterwards so you don't have to.

请注意,当您使用with它打开文件时,它会在之后自行关闭,因此您不必这样做。

回答by Vivek Sable

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 floatto convert stringvalue 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.
  1. 以读取模式读取文件。
  2. 通过readlines()或迭代行readline()
  3. 使用split(",")方法来分割线'
  4. 使用float转换string价值float。OR 我们也可以使用eval()
  5. 使用 listappend()方法将元组附加到列表。
  6. 使用 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])