如何打印所有文件数据

时间:2017-06-06 22:12:38

标签: python file

我试图打印所有文件数据,但起初它没有显示任何内容......为什么?如果我运行它几次它会显示没有第一次输入的数据......

class Data:

    def __init__(self):

        self.add = open("user_data.txt", "a")
        self.add.write("data")

    def add_data(self, user_name, password):

        self.add.write(user_name)
        self.add.write(",")
        self.add.write(password)
        self.add.write(";")
        self.read = open("user_data.txt", "r")

    def show_file(self):

        print self.read.read()


d = Data()
d.add_data("asdv", "safvas")
d.show_file()

1 个答案:

答案 0 :(得分:0)

您需要在写入文件后关闭文件。此外,您应该打开文件以便在show_file()方法中阅读:

 class Data:

def __init__(self):

    self.add = open("user_data.txt", "a")
    self.add.write("data")
    self.add.close()

def add_data(self, user_name, password):
    self.add = open('user_data.txt', 'a')
    self.add.write(user_name)
    self.add.write(",")
    self.add.write(password)
    self.add.write(";")
    self.add.close()

def show_file(self):
    self.read = open("user_data.txt", "r")
    print self.read.read()


d = Data()
d.add_data("asdv", "safvas")
d.show_file()