3

I am developing a program, and one of the options is to save the data. Although there is a thread similar to this, it was never fully resolved ( Creating file loop ). The problem is, the program does not recognise duplicate files, and I don't know how to loop it so that if there is a duplicate file name and the user does not want to overwrite the existing one, the program will ask for a new name. This is my current code:

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
2

3 Answers 3

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

This holds a boolean variable file_selected.

First, it asks the user for a file name. If this file exists and the user doesn't want to override it it continues (stops the current iteration and continues to the next one), so the user is asked again to enter a file name. (pay attention that the confirmation will execute only if the file exists because of lazy evaluation)

Then, if the file doesn't exist or the user decided to override it, file_selected is changed to True, and the loop is stopped.

Now, you can use the variable file_path to open the file

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

Sign up to request clarification or add additional context in comments.

Comments

0

Although the other answer works I think this code is more explicit about file name usage rules and easier to read:

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

4 Comments

I tried your code and it seems to be working (thank you). At the moment, everything is written to the file like: my_file.write("hello") . Will I need to change this with regards to the 'fp'? What does the 'fp' achieve in the code?
You used the same variable name for the file name and the file object... I just invented a different name "fp" for the file object (exposing my C roots I think!) without thinking about it. You could change "fp" to "my_file" and it would work like your original code. But consider using a different variable name for the file object as it makes reading the code later more clear.
Also, I demonstrated a "with" clause for opening files. When the clause terminates, the file is closed automatically.
Ok thank you. As I'm not doing anything very complicated with the file, I think I will just change the 'fp' to 'my_file'. This is the last part of my program, so I'm very happy to have finally finished it with your help
0

This is how I advise to do it, especially when you have event driven GUI app.



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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.