-1

假设我有一个名为 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的新手,这个任务已经交给我了。请帮帮我?

4

1 回答 1

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
于 2013-10-21T06:49:11.140 回答