How to deal with file in python without nested exceptions
I'm writing a python script to perform some basic CM functions like tagging in subversion. The only error checking I know how to do in python is by catching exceptions. As write code to tests for existence of various files and directories, I get all these nested try/except blocks.
try:
os.stat("dist")
print "mv " + distname + " dist"
try:
os.remove("dist/"+distname)
except:
pass
shutil.move([distname, "dist"])
except:
# Code if dist didn't exist before we got here
Is there a better way to write this--like wit开发者_Go百科h if-statements instead of exception blocks--or is this just the way Python works?. I really hate that I have logic implemented as exception blocks.
The other approach is to check to see if the file exists before attempting to perform operations on it, which may help eliminate some of your try/except blocks. You can use os.path.exists() for that. There are other functions in os.path which you may find useful as well.
That being said, Python is designed to work with exceptions under the EAFP (Easier to Ask Forgiveness than Permission) principle so there will certainly be situations where you will need to catch exceptions.
On another note I would also recommend against try/except blocks with no qualifiers since that would catch any type of exception rather than just errors relating to file access.
Look at using Python's with statement.
精彩评论