On May 2, 9:40 am, pyt...@bdurham.com wrote:
Bad file names, i.e. filenames the OS considers illegal, will cause
functions in the os.path module to raise an error.
Example:
import os.path
print os.path.getsize( 'c:/pytest/*.py' )
On Windows XP using Python 2.5.2 I get the following traceback:
Traceback (most recent call last):
File "<string>", line 74, in run_nodebug
File "<Module1>", line 3, in <module>
File "C:\Python\lib\ntpath.py", line 228, in getsize
return os.stat(filename).st_size
WindowsError: [Error 123] The filename, directory name, or volume label
syntax is incorrect: 'c:/pytest/*.py'
Since there are many places a user can enter a path name (interactively,
via config files, etc) in most applications, is there an os sensitive
function that can be used to detect bad file names?
As a matter of best practice, how do you wrap your use of file and path
names to prevent unexpected failures? (There has to be a better
alternative than try/except blocks around each use of an os.path
function in one's code?)
Thanks,
Malcolm
What do you find troubling about try/except?
Compare:
import os.path
path = raw_input("enter a path:")
if isvalidpath(path): # this is a made up name
print os.path.getsize(path)
else:
# Do something else
To:
import os.path
path = raw_input("enter a path:")
try:
print os.path.getsize(path)
except WindowsError:
# Do something else
Now, I can understand if you don't like the "WindowsError" as that is
obviously platform specific. The try/except pattern however is the way
errors are handled in python and the best and most appropriate way to
deal with it. The above example just shows that at the very least
there isn't a significant difference in code size between the two
methods.
I don't know what the equivalent error is called in *nix but assume it
is PosixError (it isn't), then it would just be written this way:
import os.path
path = raw_input("enter a path:")
try:
print os.path.getsize(path)
except (WindowsError, PosixError):
# Do something else
You don't _always_ need to wrap os.path functions with try/except. You
only need to wrap where there is reason to expect that the input might
be prone to error. In those cases the alternative is what? wrapping it
in a if/else instead? How is that better?
Matt