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



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

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打开文件

免责声明:此代码未经测试,只能在理论上运行。

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

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('hellon')

我建议这样做,尤其是当你有事件驱动的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()

相关内容

  • 没有找到相关文章

最新更新