如何在文件中创建数据对象?蟒蛇

时间:2013-10-21 06:41:03

标签: python

假设我有一个名为abc.txt的文件,其中包含以下数据

Nathan  Johnson 23 M
Mary    Kom     28 F
John    Keyman  32 M
Edward  Stella  35 M

如何在文件中创建数据(记录)的对象?

我做过的代码。我并不认为在文件中创建数据对象

class Records:
    def __init__(self, firstname, lastname, age, gender):
        self.fname = firstname        
        self.lname = lastname 
        self.age = age 
        self.gender = gender
    def read(self):
        f= open("abc.txt","r")
        for lines in f:
            print lines.split("\t") 

我应该怎么做?我是python的新手,这个任务已经给了我。请问我帮忙吗?

1 个答案:

答案 0 :(得分:3)

虽然你在这里使用了一个对象,namedtuple会更合适。

# Creating the class
class Records:
    def __init__(self, firstname, lastname, age, gender):
        self.fname = firstname
        self.lname = lastname
        self.age = age
        self.gender = gender

# Using open to open the required file, and calling the file f,
# using with automatically closes the file stream, so its less
# of a hassle.
with open('object_file.txt') as f:
    list_of_records = [Records(*line.split()) for line in f]  # Adding records to a list

for record in list_of_records:
    print record.age  # Printing a sample