如何将其写入文件

时间:2019-01-08 14:41:09

标签: python

class PersonalInfo:

def set_titles(self, title):
    self.__titles = title

def set_names(self, name):
    self.__names = name

def set_addresses(self, add):
    self.__addresses = add

def set_ages(self, age):
    self.__ages = age

def set_numbers(self, number):
    self.__numbers = number

# Accessor methods
def get_titles(self):
    return self.__titles

def get_names(self):
    return self.__names

def get_addresses(self):
    return self.__addresses

def get_ages(self):
    return self.__ages

def get_numbers(self):
    return self.__numbers


def main():
# references PersonalInfo object
info = PersonalInfo()

# stores values in the object
info.set_titles(input("Enter Mr, Mrs, Miss:"))
info.set_names(input("Enter full name:"))
info.set_addresses(input("Enter address:"))
info.set_ages(input("Enter age:"))
info.set_numbers(input("Enter number:"))



#displays values stored in object's fields
print("Name: " + info.get_titles() + " " + info.get_names() + "\n"
+"Address: " + info.get_addresses() + "\n"
+ "Birth: " + info.get_ages() + "\n"
+ "Number: " + info.get_numbers() + "\n")

main()

main()

我希望将其打印2次,因为我有2位用户将回答问题,但是我似乎无法理解如何将输入答案保存在文本文件中。有人可以给我一个例子吗? 我真是个菜鸟

2 个答案:

答案 0 :(得分:1)

将main()更改为 init (self):如果需要运行两次,请调用两次。您可以编写一种将数据输出到文件的方法,而不是将其包含在 init 中。

def __init__(self):

    # stores values in the object
    self.title = self.set_titles(input("Enter Mr, Mrs, Miss: "))
    self.name = self.set_names(input("Enter full name: "))
    self.age = self.set_ages(input("Enter age: "))
    self.address = self.set_addresses(input("Enter address: "))
    self.number = self.set_numbers(input("Enter number: "))

    # displays values stored in object's fields
    print("Name: " + self.get_titles() + " " + self.get_names() + "\n"
    +"Address: " + self.get_addresses() + "\n"
    + "Birth: " + self.get_ages() + "\n"
    + "Number: " + self.get_numbers() + "\n")

    # Appends data to file
    outfile = open('data_from_user.txt','a')
    outfile.write("Name: " + self.get_titles() + " " + self.get_names() + "\n")
    outfile.write("Address: " + self.get_addresses() + "\n")
    outfile.write("Birth: " + self.get_ages() + "\n")
    outfile.write("Number: " + self.get_numbers() + "\n")
    outfile.close()

person_1 = PersonalInfo()
person_2 = PersonalInfo()

答案 1 :(得分:0)

# storing data inside string 
string =  'NAME: {} \n Address: {} \n Birth: {} \n Number: {} \n'.format(info.get_titles(),info.get_names(),
info.get_addresses(),info.get_ages(),info.get_numbers())
# printing 2 times
print(string,string,sep='\n')
# writing in a file
x = open('filename','a')
x.write(string)
x.close()