我正在开发一个程序,其中一个选项是保存数据。尽管存在类似于此的线程,但它从未完全解析(Creating file loop)。问题是,程序无法识别重复文件,我不知道如何循环它,以便如果文件名重复且用户不想覆盖现有文件名,程序将要求一个新名字。这是我目前的代码:
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
答案 0 :(得分:1)
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
打开文件
免责声明:此代码未经过测试,只有理论上才有效。
答案 1 :(得分:0)
虽然其他答案有效,但我认为此代码更明确地涉及文件名使用规则并且更易于阅读:
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')
答案 2 :(得分:0)
我建议这样做,特别是当你有事件驱动的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()