0

How can I ask the user for a file name and if it already exists, ask the user if they want to overwrite it or not, and obey their request. If the file does not exist, a new file (with the selected name) should be created. From some research on both the Python website and Stack Overflow, I've come up with this code

try:
    with open(input("Please enter a suitable file name")) as file:
        print("This filename already exists")

except IOError:
    my_file = open("output.txt", "r+")

But this will not run in Python, and doesn't do everything I want it to do.

5
  • Did you forget a ) right before as file? Commented Jul 10, 2016 at 16:22
  • What error does it show? Commented Jul 10, 2016 at 16:23
  • Are you concerned with race conditions of checking for file existence? Commented Jul 10, 2016 at 16:27
  • I added the ) by the as file so now it will run, but when asking for a file name it will automatically say it has been used before, even if it hasn't Commented Jul 10, 2016 at 16:37
  • Race conditions : there's lots of different things (overwriting files, creating files, all in a while loop, checking for previous file existence etc) so I'm just a bit stuck ! Although there are solutions to most of those issues, I'm struggling to apply and combine them for my own use Commented Jul 10, 2016 at 16:56

2 Answers 2

1

Alternative soltution would be (however the user would need to provide a full path):

import os

def func():
    if os.path.exists(input("Enter name: ")):
        if input("File already exists. Overwrite it? (y/n) ")[0] == 'y':
            my_file = open("filename.txt", 'w+')
        else:
            func()

    else:
    my_file = open("filename.txt", 'w+')

Don't forget to close the file object when it's not needed anymore with my_file.close().

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

11 Comments

Hi I tried your solution in a separate python file just on its own and the following error came up Enter nametesting Traceback (most recent call last): line 6, in <module> my_file = open("filename.txt", 'r+') FileNotFoundError: [Errno 2] No such file or directory: 'filename.txt'
I changed that, and now this error appears my_file = open("filename.txt", 'r+') FileNotFoundError: [Errno 2] No such file or directory: 'filename.txt'
The error message still has 'r+' in it. Did you save the script before running it?
Isn't os.path.isfile a better choice since OP wants to check for regular files?
@sxnwlfkk I thought I had edited, but clearly hadn't. Done it again and it seems to work, but when I enter the same name, the program just accepts it
|
1

You can use os.path.exists to check if a file already exists are not.

if os.path.exists(file path):
    q = input("Do you want to overwrite the existing file? ")
    if q == (your accepted answer):
       #stuff
else:
    #stuff

You could do this with a try / except if you want to abide by the whole "easier to ask for forgiveness" motto, but I think this is cleaner.

5 Comments

What do you put in the (file path) ?
Isn't os.path.isfile a better choice since OP wants to check for regular files?
You could do this as one option file_path= input("Specify the file path")
Why do they need to specify the file path?
Why do you mean why do they need to specify a file path? Your entire question centers around doing this and then checking for existence etc....

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.