简体   繁体   English

将文件作为元组列表读取

[英]Read file as a list of tuples

I want to read a text file using Python. 我想用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: 我的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']

One of the most efficient way to read delimited data like this is using numpy.genfromtxt . 读取这样的分隔数据的最有效方法之一是使用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 否则你可以使用列表推导逐行读取,拆分',' ,将值转换为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它会照顾自己之后关闭,所以您不必这样做。

Yes Cyber solution is best. 是的Cyber​​解决方案是最好的。

For beginners 对新手而言

  1. Read file in Read mode. 在读取模式下读取文件。
  2. Iterate lines by readlines() or readline() 通过readlines()readline()迭代行
  3. Use split(",") method to split line by ' 使用split(",")方法将线条拆分为'
  4. Use float to convert string value to float . 使用floatstring值转换为float OR We can use eval() also. 或者我们也可以使用eval()
  5. Use list append() method to append tuple to list. 使用list append()方法将元组追加到列表中。
  6. Use try except to prevent code from break. 使用try除了防止代码中断。

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()从文件中读取一行。

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM