简体   繁体   English

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

[英]Getting input from user and writing it to a text file

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:")

I can't get my elif statement "Explain why" to print to my text file.我无法将我的elif语句“解释原因”打印到我的文本文件中。 Can anyone help me?谁能帮我? I've tried everything but nothing works so I'm stuck.我已经尝试了一切,但没有任何效果,所以我被卡住了。

To write in your text file, you should use f.write instead of printing (which shows on the console).要写入文本文件,您应该使用f.write而不是打印(显示在控制台上)。 And as stated in the comments, remember to close the file when the program finished.并且如评论中所述,请记住在程序完成后关闭文件。

Also the working status is set in User1_working_status variable, and your if statement condition reads user1_name .此外,工作状态设置在User1_working_status变量中,您的 if 语句条件读取user1_name

From what I understand, you want to create and append all the information to a text file.据我了解,您想创建所有信息并将其附加到文本文件中。 For the Explain why part, you should store the information to a variable and then write to file.对于Explain why部分,您应该将信息存储到变量中,然后写入文件。 If you use the with context manager for file I/O, you would not have to close the file explicitly.如果对文件 I/O 使用with上下文管理器,则不必显式关闭文件。

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") 

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM