473,396 Members | 2,139 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Preventing 'bad' filenames from raising errors in os.path

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
Jun 27 '08 #1
4 3227
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
Jun 27 '08 #2
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)
The common base class to use here is actually OSError. WindowsError is
a subclass thereof.

Regards,
Martin
Jun 27 '08 #3
py****@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' )
The issue, I think, is there's no function that checks
syntax of a path name without checking with the underlying OS
to see if the file exists.

If, say, you're writing a GUI tool for setting up some configuration,
you'd want to do input validation on fields without actually
accessing the files.

John Nagle
Jun 27 '08 #4
Matimus and John,

Thank you both for your feedback.

Matimus: I agree with your analysis. I blame lack of caffeine for my
original post :)

Regards,
Malcolm
Jun 27 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: hokiegal99 | last post by:
This script works as I expect, except for the last section. I want the last section to actually remove all spaces from the front and/or end of filenames. For example, a file that was named " test ...
3
by: Kevin Ollivier | last post by:
Hi all, On Windows, it's very common to have a string of long directories in the pathname for files, like "C:\Documents and Settings\My Long User Name\My Documents\My Long Subdirectory...
2
by: rbutch | last post by:
guys, i need a little help with this. this is working (well sort of) i get the info, but it's not moving to a new line as it iterates thru the array and all of the fields are like ONE HUGE LONG...
1
by: Klaus Jensen | last post by:
Hi! I often raise my own errors in code, and I just use ErrorNumber 1, since I do not use this number for anything (like maintaining a table of errornumbers or whatever). I then started...
0
by: ColdCoffee | last post by:
Scenario: My computer: name : PrasComp pass : Pras123 Domain : XYZ Computer I wanna access: Name : AnoComp pass : #Pras
7
by: oscartheduck | last post by:
Hi folks, I'm trying to alter a program I posted about a few days ago. It creates thumbnail images from master images. Nice and simple. To make sure I can match all variations in spelling of...
3
by: Torsten Bronger | last post by:
Hallöchen! I'd like to map general unicode strings to safe filename. I tried punycode but it is case-sensitive, which Windows is not. Thus, "Hallo" and "hallo" are mapped to "Hallo-" and...
6
by: kimiraikkonen | last post by:
Hello, I have a listbox and folder browser control. I need to display all .mp3 files' pathes into listbox. It was Ok with openfiledialog but how can list all .mp3 extension- having files into...
2
by: =?Utf-8?B?SmVzcGVyLCBEZW5tYXJr?= | last post by:
Hi, I work in a company where we tend to use very deep folder structures and long descriptive file names due to the nature of the analysis that we make. I've made a program that recursively...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.