Python挑战25
为课余俱乐部写一个注册计划;它应该询问用户以下详细信息并将其存储在文件中:
对于上述任务,我编写了以下python代码:
# Python Challenge 25
print ("Hello user, this is a virtual application form"
"\nfor joining after-school clubs at -Insert school name here-")
first_name = input("\n\nPlease input your first name:")
last_name = input("Please input your last name:")
gender = input("Please input your gender:")
form = input("Please input your form name:")
club = input("What after-school club would you like to attend?\n")
file = open("application-form.txt", "w")
file.write(first_name)
file.write (last_name)
file.write (gender)
file.write (form)
file.write (club)
file.close()
print (first_name, "Thank you for taking your time to fill this virtual form"
"\nall the information has been stored in a file to maintain confidentiality")
上述代码的结果示例:
我的问题
保存文本文件后,所有用户输入都存储在一行中,有没有办法可以将每个输入放在一个单独的行上?
是否有更有效的方法来编写上述代码?
答案 0 :(得分:1)
1)将file.write(first_name)
替换为file.write(first_name + '\n')
或稍后添加行file.write('\n')
。
2)我不认为代码可以运行得更快,我认为它不需要,但就代码质量/长度而言,我会像这样编写文件写入部分:
with open("application-form.txt", "w") as f:
for item in [first_name, last_name, gender, form, club]:
f.write(first_name + '\n)
答案 1 :(得分:1)
与print
相反,write
不会自动附加行尾。您可以在写入之间添加file.write("\n")
以插入行的末尾。
或者,您可以使用join
创建一个散布行尾的单个字符串,并编写该单个字符串。
示例:
file.write("\n".join([line1, line2, line3]))
答案 2 :(得分:0)
至于使代码更高效/更整洁,您可以使用函数来请求和存储数据:
def get_info(prompts):
file = open("application-form.txt", "w")
for prompt in prompts:
file.write(input(prompt))
file.write('\n')
print ("Hello user, this is a virtual application form"
"\nfor joining after-school clubs at -Insert school name here-")
prompts = ["\n\nPlease input your first name:",
"Please input your last name:",
"Please input your gender:",
"Please input your form name:",
"What after-school club would you like to attend?\n"]
get_info(prompts)
print ("Thank you for taking your time to fill this virtual form"
"\nall the information has been stored in a file to maintain confidentiality")
不幸的是,为了做到这一点,我不得不在谢谢你(最后一个打印声明)中取出first_name
电话。如果你绝对需要的话,那你到目前为止可能会更好。