Check if a file exists using Python

To check if a file exists or not is an extremely easy task to be done in Python, but there are some tricky parts… Below is one of the possible approaches to this.

The script below to check if a file exists.

The variable isFile is set to True file passed has argument exists or False if it doesn’t. The problem with this approach is, if you don’t pass the full path of the file (example: fileName = “file.txt” will return false, even if the file exists.

To use the relative path, first we need to get the directory where the script is running:

The variable __FILE__ exists in Python and holds the reference to the script file that is being executed.

If we join the two approaches, we can implement a pseudo-retry pattern.

The function above will try to verify whether the file passed via argument exists. If it doesn’t, it concatenates the path to the current script’s path and tries again.


The following two tabs change content below.
Breno RdV
Please allow me to introduce myself...I'm a former psychologist, with almost a decade worth of experience in Human Resources and People Management. Now a developer/software analyst working with PowerBuilder, C#, PowerShell and currently expanding to the world of Python, Xamarin, PHP Angular and (why not?) Unity.



Posted in Python and tagged , , , .