Python – Check if a File Exists

If you need your script to check if a file exists, for example before attempting to create one, it is relatively straight forward and easy to do so using the ‘os’ module. Below is a snippet of code that all it will do is check if a particular hard coded file exists, if it does exist it will return ‘True’ and if it does not it will return ‘False’. All of the code below is cross platform, I have tested it on a Windows computer and a Linux computer.

And when running this script on a windows computer we will get the output below.

 

Now if I edit that file path in the last line fromĀ  ‘C:/windows/system32/cmd.exe’ to something that does not exist on my system like ”C:/windows/system32/nofilehere.exe’ we will see the output below.

 

As you can see in the code above I condensed checking for the file and printing the results to a single line, you could also store the output in a variable and then call that variable to preform some other sort of logic, the example is below will just change the way the program tells the user if the file exists or not.

And we can see by the output below, it works as we would expect

Be the first to comment

Leave a Reply

Your email address will not be published.


*