473,569 Members | 2,747 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(filenam e).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 3244
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(filenam e).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("ente r a path:")
if isvalidpath(pat h): # this is a made up name
print os.path.getsize (path)
else:
# Do something else

To:

import os.path

path = raw_input("ente r a path:")
try:
print os.path.getsize (path)
except WindowsError:
# Do something else

Now, I can understand if you don't like the "WindowsErr or" 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("ente r 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 "WindowsErr or" 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
6726
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 " would be renamed "test" (the 2 spaces before and after the filename removed). Any suggestions on how to do this? import os, re, string print...
3
2450
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 Name\...". For a wxPython application I'm working on, this has actually caused me to run into what appears to be Python's pathname length limit for opening...
2
8665
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 string 'declare an array Dim filenames() As String filenames = Directory.GetFiles("C:\Re_Class") Dim i, o As Integer Dim info As String
1
1409
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 wondering... Is this an okay use of raising errors? Should I use a certain range of numbers for some reason? Is there a best practice for raising errors...
0
1403
by: ColdCoffee | last post by:
Scenario: My computer: name : PrasComp pass : Pras123 Domain : XYZ Computer I wanna access: Name : AnoComp pass : #Pras
7
2337
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 jpeg, and different cases, I'm using regular expressions. The code is currently:
3
2210
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 "hallo-", however, I need uppercase Latin letters being encoded, too, and the encoding must contain only lowercase Latin letters, numbers, underscores,...
6
3144
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 my listbox using folder browser control. A sample code would be great.
2
1935
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 descends into these folders to do some search stuff. However, I receive an exception trown from a FileInfo object when I'm deep down the mine shaft...
0
7609
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8118
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6278
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5504
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2107
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.