创建文件循环
Creating file loop
如何向用户询问文件名,如果已经存在,询问用户是否要覆盖它,并服从他们的要求。如果该文件不存在,则应创建一个新文件(具有选定的名称)。
通过对 Python 网站和 Stack Overflow 的一些研究,我想出了这段代码
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 中,并且不会做我想让它做的所有事情。
您可以使用 os.path.exists
来检查文件是否已经存在。
if os.path.exists(file path):
q = input("Do you want to overwrite the existing file? ")
if q == (your accepted answer):
#stuff
else:
#stuff
你可以试试 / 除非你想遵守整个 "easier to ask for forgiveness" 座右铭,但我认为这更干净。
替代解决方案是(但用户需要提供完整路径):
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()
。
如何向用户询问文件名,如果已经存在,询问用户是否要覆盖它,并服从他们的要求。如果该文件不存在,则应创建一个新文件(具有选定的名称)。 通过对 Python 网站和 Stack Overflow 的一些研究,我想出了这段代码
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 中,并且不会做我想让它做的所有事情。
您可以使用 os.path.exists
来检查文件是否已经存在。
if os.path.exists(file path):
q = input("Do you want to overwrite the existing file? ")
if q == (your accepted answer):
#stuff
else:
#stuff
你可以试试 / 除非你想遵守整个 "easier to ask for forgiveness" 座右铭,但我认为这更干净。
替代解决方案是(但用户需要提供完整路径):
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()
。