Python:从文件中读取行,拆分它并更改对象

时间:2015-10-01 18:12:49

标签: python object text-files

让我们想象一下,我有一个包含1000行的文本文件。所有这些都是这样的:

FirstName:SecondName:1:2:3:4

":"可以替换为任何其他符号,我有1000个对象的列表:

class RECORD:
    FNAME = "default"
    SNAME = "default"
    M1 = 0;
    M2 = 0;
    M3 = 0;
    M4 = 0;

    def outname(self):
        print (self.FNAME + self.SNAME)

LIST = []
for i in range(1000):
    LIST.append(RECORD(i))

所以,我想读取这个文件,并用第一行的第二个对象和第二行的字符串和整数填充第一个对象。 我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:2)

对于简单的类(与您的类似),collections.namedtuple通常很有用:

from collections import namedtuple

Record = namedtuple("Record", "FNAME SNAME M1 M2 M3 M4")
with open("records.txt") as record_file:
    records = [Record(*line.split(':')) for line in record_file]

print records[3].FNAME  # For example

此外,您可能希望将类似的项目存储为序列,因此每个记录都是名称列表和整数列表。这是一个版本。

from collections import namedtuple
from pprint import pprint

Record = namedtuple("Record", "names m")
records = []
with open("records.txt") as record_file:
    for line in record_file:
        line = line.split(':')
        line = line[0:2] , [int(i) for i in line[2:]]
        line = Record(*line)
        records.append(line)

print records[3].names[0] # Same as first example
pprint (records)          # pretty-print entire list

答案 1 :(得分:1)

我认为你正在寻找这样的东西:

class Record(object):
    """docstring for Record"""
    def __init__(self, FNAME, SNAME, M1, M2, M3, M4):
        super(Record, self).__init__()
        self.FNAME = FNAME
        self.SNAME = SNAME
        self.M1 = M1
        self.M2 = M2
        self.M3 = M3
        self.M4 = M4

with open('your_file_name') as f:
    LIST = [Record(*(line.split(':'))) for line in f]

所有工作都发生在最后一行。文件列表理解为您提供行列表。每行在:上拆分,并通过解包传递给Record构造函数。

答案 2 :(得分:0)

试试这段代码。我试图让它变得非常pythonistic仍然接近你从C ++知道的东西。但是请尝试在Python中沉浸一点......

  mpint
  Represents multiple precision integers in two's complement format,
  stored as a string, 8 bits per byte, MSB first.  Negative numbers
  have the value 1 as the most significant bit of the first byte of
  the data partition.  If the most significant bit would be set for
  a positive number, the number MUST be preceded by a zero byte.
  Unnecessary leading bytes with the value 0 or 255 MUST NOT be
  included.  The value zero MUST be stored as a string with zero
  bytes of data.
  eg: 80(hex)                 00 00 00 02 00 80

答案 3 :(得分:-1)

import csv

class Record(object):

    def __init__(self, fname = 'default', sname = 'default', m1 = 0, m2 = 0, m3 = 0, m4 = 0):

        self.fname = fname
        self.sname = sname
        self.m1 = int(m1)
        self.m2 = int(m2)
        self.m3 = int(m3)
        self.m4 = int(m4)

    def get_name(self):
        return '{0} {1}'.format(self.fname, self.sname)

records = []
reader = csv.reader(open('file.txt', 'rb'), delimiter = ':')
for row in reader:
    records.append(Record(*row))

for record in records:
    print(record.get_name())
    #FirstName SecondName