文件保存问题 PYTHON - 文件重复?

File saving issue PYTHON - duplicate files?

我正在开发一个程序,其中一个选项是保存数据。尽管有一个与此类似的线程,但它从未完全解决 ( )。问题是,程序不识别重复的文件,我不知道如何循环它,这样如果有重复的文件名并且用户不想覆盖现有的文件,程序会要求一个新的姓名。这是我当前的代码:

print("Exporting")
import os

my_file = input("Enter a file name")
while os.path.isfile(my_file) == True:
    while input("File already exists. Overwrite it? (y/n) ") == 'n':
        my_file = open("filename.txt", 'w+')
        # writing to the file part

my_file = open("filename.txt", 'w+')
    # otherwise writing to the file part
file_selected = False
file_path = ""
while not file_selected:
    file_path = input("Enter a file name")
    if os.path.isfile(file_path) and input("Are you sure you want to override the file? (y/n)") != 'y':
        continue
    file_selected = True
#Now you can open the file using open()

这包含一个布尔变量file_selected

首先,它要求用户提供文件名。如果此文件存在并且用户不想覆盖它,它会继续(停止当前迭代并继续下一个迭代),因此会再次要求用户输入文件名。 (注意因为惰性求值,只有文件存在才会执行确认)

然后,如果文件不存在或用户决定覆盖它,file_selected 将更改为 True,并且循环停止。

现在,您可以使用变量 file_path 打开文件

Disclaimer: This code is not tested and only should theoretically work.

虽然其他答案有效,但我认为这段代码对文件名使用规则更明确并且更易于阅读:

import os

# prompt for file and continue until a unique name is entered or
# user allows overwrite
while 1:
    my_file = input("Enter a file name: ")
    if not os.path.exists(my_file):
        break
    if input("Are you sure you want to override the file? (y/n)") == 'y':
        break

# use the file
print("Opening " + my_file)
with open(my_file, "w+") as fp:
    fp.write('hello\n')

这就是我建议的做法,尤其是当您有事件驱动的 GUI 应用程序时。



import os

def GetEntry (prompt="Enter filename: "):
    fn = ""
    while fn=="":
        try: fn = raw_input(prompt)
        except KeyboardInterrupt: return
    return fn

def GetYesNo (prompt="Yes, No, Cancel? [Y/N/C]: "):
    ync = GetEntry(prompt)
    if ync==None: return
    ync = ync.strip().lower()
    if ync.startswith("y"): return 1
    elif ync.startswith("n"): return 0
    elif ync.startswith("c"): return
    else:
        print "Invalid entry!"
        return GetYesNo(prompt)

data = "Blah-blah, something to save!!!"

def SaveFile ():
    p = GetEntry()
    if p==None:
        print "Saving canceled!"
        return
    if os.path.isfile(p):
        print "The file '%s' already exists! Do you wish to replace it?" % p
        ync = GetYesNo()
        if ync==None:
            print "Saving canceled!"
            return
        if ync==0:
            print "Choose another filename."
            return SaveFile()
        else: print "'%s' will be overwritten!" % p
    # Save actual data
    f = open(p, "wb")
    f.write(data)
    f.close()