问题描述
如何向用户询问文件名以及该文件名是否已存在,请询问用户是否要覆盖它,并听从他们的请求.如果该文件不存在,则应创建一个新文件(具有所选名称).通过对Python网站和Stack Overflow的一些研究,我得出了这段代码
How can I ask the user for a file name and if it already exists, ask the user if they want to overwrite it or not, and obey their request. If the file does not exist, a new file (with the selected name) should be created.From some research on both the Python website and Stack Overflow, I've come up with this code
try:
with open(input("Please enter a suitable file name")) as file:
print("This filename already exists")
except IOError:
my_file = open("output.txt", "r+")
但这将无法在Python中运行,并且无法完成我希望它执行的所有操作.
But this will not run in Python, and doesn't do everything I want it to do.
推荐答案
替代解决方案是(但是用户需要提供完整路径):
Alternative soltution would be (however the user would need to provide a full path):
import os
def func():
if os.path.exists(input("Enter name: ")):
if input("File already exists. Overwrite it? (y/n) ")[0] == 'y':
my_file = open("filename.txt", 'w+')
else:
func()
else:
my_file = open("filename.txt", 'w+')
别忘了当不再需要使用 my_file.close()
关闭文件对象时.
Don't forget to close the file object when it's not needed anymore with my_file.close()
.
这篇关于创建文件循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!