I have a question about error checking in Python. Suppose I have a function that takes the file path as input:
def myFunction (file path): infile = open (filepath) #etc etc ...
< / Pre>A possible pre-condition should be that the file exists.
There are some possible ways to check this pre-condition, and I'm wondering what is the best way to do this.
i) Check with a statement:
if not os.path.exists (filepath): raise IOException ('file does not exist:% s'% filepath)
This is the way that I will do this generally, although the same IOException will be raised by Python if the file does not exist, even if I do not raise it.
ii) Use the condition to use the condition:
os.path.exists (file path) says, 'file does not exist:% s '% Filepath'
The use of objection is the way to check for "standard" pre / postcinding, so I am trying to use these. However, it is possible that these sounds are closed when -O flag is used during execution, which means that this test can potentially be stopped and it seems risky.
iii)
The reason for this is that if the file path is not in existence, an exception will also be generated anyway and the exception message is sufficient, to know that the file does not exist
I'm just thinking what is the standard practice from above which I should use for my code.
If you want to increase the exception, options iii
: < / P>
Use def myFunction (file path): with open (file path) as infile: pass
to handle exceptions in a particular way , block ...
block:
def myFunction (filepath): try: infile as open (file path): pass except for IOError Do: # Special Ha Ndling Code Here
Under any circumstances, file It is better to check existence first (option i
or ii
), because it is possible when a probe or claim is made and when the dragon tries to open the file, it is possible That file can be removed, or can be changed (such as with symlinks), which can reach the bug or security hole.
In addition, as Python 2.6, the best practice when opening files with opening (...)
syntax guarantees that the file will be closed, Even with with
-blok
If there is an exception, you can use the syntax with
if you enter
with
Comments
Post a Comment