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
with open(input("Please enter a suitable file name")) as file:
print("This filename already exists")
my_file = open("output.txt", "r+")
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) ") == '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