Check file availability in Python 3

I would like to know how I can check if a file exists based on user input, and if not, I would like to create it.

so I would have something like:

file_name = input('what is the file name? ') 

then I would like to check if the file name exists.

If the file name exists, open the file for writing or reading, if the file name does not exist, create the file based on user input.

I know the most basic files, but not how to use user input to validate or create a file.

+6
source share
2 answers

You can use the os module:

Like this: os.path.isfile ():

 import os.path os.path.isfile(file_path) 

Or using os.path.exists ():

 if os.path.exists(file_name)==True: print("I get the file >hubaa") 

if the file does not exist: (return False)

 if os.path.exists(file_name)==False: print("The File s% it not created "%file_name) os.touch(file_name) print("The file s% has been Created ..."%file_name) 

And you can write simple code based on (try, Except):

 try: my_file = open(file_name) except IOError: os.touch(file_name) 
+9
source

To do what you asked:

You need to look at the os.path.isfile() function and then the open() function (passing your variable as an argument).


However, as @LukasGraf notes, this is usually considered less than ideal because it introduces a condition if something else you created a file in the interval when you check to see if it exists and when you open it.

Instead, the usual preferred method is to simply try to open it and catch the exception that is thrown if you cannot:

 try: my_file = open(file_name) except IOError: # file couldn't be opened, perhaps you need to create it 
+1
source

All Articles