我在检查用户输入的文件名是否已存在时遇到问题。这是我当前正在运行的代码,但是当我正确运行代码并使用已存在的名称保存数据时。它会打印正确的错误标题"此文件已存在"并将它们返回到程序菜单。我想知道我怎么能拥有它。有没有办法可以让程序再次要求用户重新输入文件名?
if Menuchoice =='4':
if popJuveniles ==0:
print("please take part in option 1 before running option 4")
else:
if csvdata ==1:
print("please take part in option 3 before trying to save the file")
else:
import csv
#file_name=input("What would you like to call your file?")
filename1=input("what would you like to call your file?")
if os.path.isfile(filename1):
print("This file already exists")
csvext='.csv'
filename=filename1+csvext
with open(filename,'a') as genfile:
insects_writer = csv.writer(genfile)
insects_writer.writerow(csvdata)
答案 0 :(得分:1)
如果您想快速回答,我会使用while
循环,直到名称正确。
例如:
while os.path.isfile(filename1):
print("This file already exists")
filename1=input("what would you like to call your file?")
请注意,由于各种原因,您不应经常使用while
。