In Python, it can often be seen that you will hit errors, known as exceptions
, when running code. For this reason, the try/catch
has been deployed.
Here is a snippet of code I use in my day-to-day that clears files from a directory, or skips if they do not exist.
def DeleteFile(Path_):
"""Deletes saved project AND its corresponding "files" folder."""
try: #deletes the folder
os.remove(Path_)
except OSError:
pass
try: #deletes the file, using some fancy python operations to arrive at the filename
shutil.rmtree(os.path.join(os.path.dirname(Path_),os.path.splitext(os.path.basename(Path_))[0])+"_files", True)
except OSError:
pass
This is a classic example of checking for if a file exists. Instead of deleting inside your try
statement, you could have try to copy the file. If it fails, it moves on to pass
, which just skips the try/catch
block.
Take note, try/catch
can be used to catch any exception, or it can be used to catch specific ones. I have OSError
scrawled in but read through them to be sure that's the one you want. If you have a specific error in a catch
and the system gives back the wrong kind of error, your try/catch
will not work the way you want it to. So, be sure. IN best case, be general.
Happy coding!
EDIT: It is worth noting that this try/catch
system is a very Pythonic way to go about things. try/catch
is very easy and popular, but your situation may call for something different.
EDIT: I'm not sure if it's worth noting this, but I realize my answer doesn't directly tell you how to check if a file exists. Instead, it assumes that it does not and proceeds with the operation anyway. If you hit a problem (i.e., it exists and you need to overwrite), you can make it so that it automatically skips over the entire thing and goes onto the next one. Again, this is only one of many methods for accomplishing the same task.