Search code examples
pythonfilewhile-loopsaving-data

File saving issue PYTHON - duplicate files?


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

Solution

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