如何使用 os.path 检查文件是否存在

2024-04-23 10:14:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我当前在检查用户输入的文件名是否已存在时遇到问题。这是我当前正在运行的代码,但是当我正确运行代码并用已经存在的名称保存数据时。它打印正确的错误标题“此文件已存在”,并将它们返回到程序的菜单。我在想我怎么能得到它。有没有办法让程序要求用户重新输入文件名?你知道吗

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)

Tags: csvto代码in程序if文件名file
1条回答
网友
1楼 · 发布于 2024-04-23 10:14:41

如果你想要一个快速的答案,我会使用while循环直到名称正确为止。你知道吗

例如:

while os.path.isfile(filename1):
    print("This file already exists")
    filename1=input("what would you like to call your file?")

但是请记住,由于各种原因,您不应该经常使用while。你知道吗

相关问题 更多 >