如何解决从函数中获取输入并将其写入.txt文件,然后创建函数以关闭文件
- 将用户的输入保存为.txt文件的最佳方法是什么?
到目前为止,我到了这一点,但是当我尝试编码 I / O 时,我陷入了困境。
# check if the sname that the user has typed is correct and save it to a new .txt file in the same folder as the .py project
sname = 'nicolas'
while True:
try:
question = input('Enter your second name:')
if question == sname:
print('Ok')
break
else:
if question != sname:
print("Please,enter your second name correctly...")
except ValueError:
print("That wasn't correct,try again...")
解决方法
您可以使用with
sname = 'nicolas'
question = input('Enter your second name:')
while question.lower() != sname:
print("Please,enter your second name correctly...")
question = input('Enter your second name:')
with open("textfile.txt","w") as f:
f.write(sname)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。