Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
文件保存问题PYTHON-重复文件?_Python_File_While Loop_Saving Data - Fatal编程技术网

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

文件保存问题PYTHON-重复文件?,python,file,while-loop,saving-data,Python,File,While Loop,Saving Data,我正在开发一个程序,其中一个选项是保存数据。虽然有一个线程与此类似,但它从未完全解析()。问题是,程序无法识别重复的文件,我不知道如何循环它,以便如果存在重复的文件名,并且用户不想覆盖现有的文件名,程序将要求使用新名称。这是我当前的代码: print("Exporting") import os my_file = input("Enter a file name") while os.path.isfile(my_file) == True: while input("File al

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

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
这将保存一个布尔变量
文件\u选中


首先,它要求用户输入文件名。如果此文件存在,并且用户不想覆盖它,它将继续(停止当前迭代并继续到下一个迭代),因此再次要求用户输入文件名。(请注意,只有由于延迟计算而存在文件时,才会执行确认)

然后,如果文件不存在或用户决定覆盖它,则所选的
file\u
将更改为
True
,循环将停止。

现在,您可以使用变量
file\u 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('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()


你能链接你提到的“类似于此”的线程吗?@nbryans我尝试了你的代码,它似乎在工作(谢谢)。目前,所有内容都会写入文件,如:my_file.write(“hello”)。我是否需要对“fp”进行更改?“fp”在代码中实现了什么?您对文件名和文件对象使用了相同的变量名。。。我只是为文件对象发明了一个不同的名称“fp”(我想是暴露了我的C根!),没有考虑它。您可以将“fp”更改为“my_file”,它的工作方式与原始代码相同。但是考虑在文件对象中使用不同的变量名,因为它以后读取代码更加清楚。此外,我演示了打开文件的“使用”子句。当子句终止时,文件将自动关闭。好的,谢谢。由于我没有对该文件做任何非常复杂的操作,我想我只需将“fp”更改为“my_file”。这是我计划的最后一部分,所以我很高兴在你的帮助下终于完成了


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