Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check for file existence in Python 3 [duplicate]

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.

like image 528
krona Avatar asked May 04 '14 17:05

krona


People also ask

How do you check if a file already exists in Python?

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 .

How do you check if file exists in Python and delete it?

Python delete file if exists To delete a file if exists in Python, use the os. path. exists() and os. remove() method.


2 Answers

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) 
like image 118
saudi_Dev Avatar answered Oct 09 '22 07:10

saudi_Dev


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 
like image 38
Amber Avatar answered Oct 09 '22 05:10

Amber