从用户处获取输入并将其写入文本文件

时间:2019-01-04 10:23:47

标签: python

f=open("test.txt","w")
f.write("PERSONALINFO"+"\n")
f.write("\n")
f.close()

f=open("test.txt","a")
f.write("Customer 1 Info:""\n")
print()

print("Customer 1 input:")
user1_title=input("Enter Mr, Mrs, Miss, Ms:")
user1_name=input("Enter fullname:")
user1_town=input("Enter town and country you live in:")
user1_age=input("Enter birth MM/DD/YY with numbers:""\n")

print()
print("Name:",user1_title + "",     user1_name,"\n""Hometown:",user1_town,"\n" "Age:", user1_age, file=f)


print("1.Student")
print("2.Not working")
User1_working_status=input("Enter working status:")



if user1_name=="1":
    print("student")
elif user1_name=="2":
    print("Not working")
    input("Please explain why:")

我无法将elif语句“解释原因”打印到我的文本文件中。谁能帮我?我已经尝试了所有方法,但没有任何效果,所以卡住了。

2 个答案:

答案 0 :(得分:0)

要写入文本文件,应使用f.write而不是打印(控制台上显示)。并且如注释中所述,请记住在程序完成后关闭文件。

还可以在User1_working_status变量中设置工作状态,并且if语句的条件为user1_name

答案 1 :(得分:0)

据我了解,您想创建所有信息并将其附加到文本文件中。对于Explain why部分,应将信息存储到变量中,然后写入文件。如果将with上下文管理器用于文件I / O,则不必显式关闭文件。

user1_title=input("Enter Mr, Mrs, Miss, Ms: ")
user1_name=input("Enter fullname: ")
user1_town=input("Enter town and country you live in: ")
user1_age=input("Enter birth MM/DD/YY with numbers:""\n")
print("1.Student")
print("2.Not working")
User1_working_status=input("Enter working status: ")


with open("test.txt", 'a+') as f:
    if User1_working_status=="1":
        f.write("{}\n{}\n{}\n{}\n".format("Name: " + user1_title + " " + user1_name, "Town: " + user1_town, "Age: " + user1_age, "Working status: student"))        
    elif User1_working_status=="2":
        explain = input("Please explain why: ")
        f.write("{}\n{}\n{}\n{}\n{}\n".format("Name: " + user1_title + " " + user1_name, "Town: " + user1_town, "Age: " + user1_age, "Working status: Not Working", "Reason: " + explain))
print("Information written to test.txt") 

希望这会有所帮助。