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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With