I would like to know how I could check to see if a file exist based on user input and if it does not, then i would like to create one.
so I would have something like:
file_name = input('what is the file name? ')
then I would like to check to see if file name exist.
If file name does exist, open file to write or read, if file name does not exist, create the file based on user input.
I know the very basic about files but not how to use user input to check or create a file.
To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .
Python delete file if exists To delete a file if exists in Python, use the os. path. exists() and os. remove() method.
if the file is not a file :(return False)
import os.path if not os.path.isFile(file_name): print("The File s% it's not created "%file_name) os.touch(file_name) print("The file s% has been Created ..."%file_name)
And you can write a simple code based on (try,Except):
try: my_file = open(file_name) except IOError: os.touch(file_name)
To do exactly what you asked:
You're going to want to look at the os.path.isfile()
function, and then the open()
function (passing your variable as the argument).
However, as noted by @LukasGraf, this is generally considered less than ideal because it introduces a race condition if something else were you create the file in the time between when you check to see if it exists and when you go to open it.
Instead, the usual preferred method is to just try and open it, and catch the exception that's generated if you can't:
try: my_file = open(file_name) except IOError: # file couldn't be opened, perhaps you need to create it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With