为什么它写在同一行?

时间:2017-01-12 11:33:35

标签: python python-3.x

为什么每次我创建一个新实例时,它都会在同一行上写入? 当我打开文件时,它只有最后一个对象属性。 我尝试使用f.seek(0,2)并且它不起作用。

class persoana(object):
    def __init__(self):
        self.nume = input("Nume:")
        self.idd = int(input("Id:"))
        self.tel = input("Telefon:")
        self.adress = input("Adresa:")
        self.write()

    def write(self):
        f = open('persoane.txt','w')
        f.write("\n" + "#" + self.nume + "," + str(self.idd) + "," + self.tel + "," + self.adress)
        f.close()

1 个答案:

答案 0 :(得分:0)

您需要以追加模式打开文件。

class persoana(object):
    def __init__(self):
        self.nume = input("Nume:")
        self.idd = int(input("Id:"))
        self.tel = input("Telefon:")
        self.adress = input("Adresa:")
        self.write()

    def write(self):
        f = open('persoane.txt','a')
        f.write("\n" + "#" + self.nume + "," + str(self.idd) + "," + self.tel + "," + self.adress)
        f.close()

此外,它首选使用with open(filename) as f格式,如下所示:

def write(self):
    with open('persoane.txt', 'a') as f:
        f.write("\n" + "#" + self.nume + "," + str(self.idd) + "," + self.tel + "," + self.adress)

如果发生异常或错误,这将管理文件的关闭。