Using try/except or if/else when copying files
file-io, python, race-condition, try-catch
Solution
Definitely the second.
It's easy to think of your program steps as sequential actions where nothing else happens in between. But that's not really how computers (at least modern non-embedded ones) work.
In between you checking that the path exists and actually trying to write to it some other program could easily come along and delete it leading to an uncaught runtime exception. This is a common concurrency bug.
So always, always use `try/catch` (or in Python's case, `try/except`) when working with the filesystem, network, or any other external resource you don't completely control.
Here is a good resource with a more in-depth explanation.
Problem
I have two methods for copying a file, which one is the most pythonic/best version? In working through an object-oriented textbook I've been told (paraphrasing here) that it's best to avoid checking and handle 'exceptional situations' when they arise. Is the way I've used `try`/`except` in the second version valid? First version using `if`/`else`: ``` if os.path.exists(dest): print("\nCopying zipfile to {}".format(dest)) shutil.copy(self.backup_zipfile_name, dest) else: print("Cannot find {}.".format(dest)) ``` Second version using `try`/`except`: ``` try: shutil.copy(self.back_zipfile_name, dest) except FileNotFoundError: print("{!r} could not be found".format(dest)) ```