PYTHON - 从文件中读取单行

时间:2013-06-17 13:20:49

标签: python io

我需要几个小时的python,我正在尝试编写一个脚本,它从一个文件(名为'peaks.dat')读取一组x,y坐标并将它们填入一个列表(类类型) );我正在定义以下内容:

class point():
    def _init_(self,x=None,y=None,k=None,f=None):
        self.x=0    # x coordinate
        self.y=0    # y coordinate
        self.k=0    # I need these for later stuff
        self.f=-1   # I need these for later stuff

但后来我找不到任何方法从文件中的一行(即两列中只有一列中的一个元素)中“选取”单个元素,而不是整行。有这样的事吗?

无论如何,我尝试将我的列拆分为两个不同的文件x.dat和y.dat,但后来我完全不知道如何从文件中单独填充我的'point'类型列表的x和y字段。 我试过了

f=open('x.dat','r')
mylist=[]
for line in f:
    mylist.append(point(line, , , )) # wrong syntax D:
f.close()

for data in mylist:
    print i.x

计划在y.dat文件中稍后使用,但在许多级别上似乎都是错误的。

P.S。如果你想举例,我来自一些C ++。

编辑:peaks.dat只有三列(我只需要前两个)数字,比如

1.2   1.6   0.4
1.5   2.1   0.3
1.1   1.0   0.5

x.dat(或y.dat)是一行数字。

3 个答案:

答案 0 :(得分:5)

根据文件的格式,您要么使用csv模块,要么使用str.split()功能。

对于某一行上以空格分隔的值,请使用str.split()

points = []

with open(inputfilename) as infile:
    for line in infile:
        row = [int(i) for i in line.split()]
        # row is now a list of integers.
        points.append(point(*row))

对于其他格式,通常csv module是最佳选择:

import csv

points = []

with open(inputfilename, 'rb') as infile:
    reader = csv.reader(infile, delimiter='\t')  # tab delimited file
    for row in reader:
        row = [int(i) for i in row]
        # row is now a list of integers.
        points.append(point(*row))

要只读两行,请使用next()两次; csv版本:

    for _ in range(2):
        row = [int(i) for i in next(reader)]
        # row is now a list of integers.
        points.append(point(*row))

next()从迭代器中获取下一个项目; infile对象和reader对象都是产生文件行或CSV行的迭代器。

或者,使用itertools.islice() utility

for row in islice(reader, 2):  # only yield the first two rows.

答案 1 :(得分:2)

使用str.split拆分行上的数据,str.split返回字符串列表。

示例:

>>> strs = "1.2   1.6   0.4"
>>> strs.split()
['1.2', '1.6', '0.4']
#use slicing as you need only first two items
>>> [float(x) for x in strs.split()[:2]] 
[1.2, 1.6]

如果您只需要每行的前两列:

mylist=[]
with open('x.dat') as f:
   for line in f:
       #apply int to the items of `str.split` to convert them into integers
       x, y = [float(z) for z in line.split()[:2]]
       mylist.append(Point(x, y))

如果您只想阅读前两行:

mylist=[]
with open('x.dat') as f:
   rows = 2
   for _ in xrange(rows):
       line = next(f)
       x, y, k = [float(z) for z in line.split()]
       mylist.append(Point(x, y, k))

对您的班级定义进行了一些更改:

class point():
   def __init__(self,x = None,y =None,k =None,f =None):
      self.x = 0 if x is None else x  #assign default value only if the value was not passed
      self.y = 0 if y is None else y
      self.k = 0 if k is None else k
      self.f = -1 if f is None else f

答案 2 :(得分:0)

这取决于文件的格式。坐标是用逗号分隔的吗? 如果是的话,那么。

with open('x.dat','r') as f:
    mylist=[]
    for line in f:
        points = line.split(",")
        mylist.append(point(int(points[0]), int(points[1]), int(points[2]),int(points[3]))) 

我确信有一种更好,更pythonic的方式来做到这一点。

你可以在这里阅读Python的'with' http://effbot.org/zone/python-with-statement.htm

如果我的回答不是你想要的,那么你可以在这里找到有用的东西,http://docs.python.org/3/library/io.html#module-io

相关问题