Case sensitive file names

Matt Gerrans mgerrans at mindspring.com
Sun Feb 22 22:10:09 EST 2004


> When opening a file with file.open(filename,"r") under Windows, I find
> that the file name is case sensitive - ...

Poppycock!   Filenames in Windows preserve case, but are *not* case
sensitive for opening, finding, etc.   That is, if you save "TEST.TXT", then
you can successfully open "test.txt".

Nevertheless, there are several answers to your question:

If you did want to get the correct-case of the file name, then you could use
glob, or win32file.FindFilesW() or something like that, then match the exact
case result with whatever you are looking for (case-sensitve or not, as you
require).

Your real problem, shown in your example is your inconsistent use of '\' or
'\\'.   If you want to use single backslashes, that fine and dandy, but you
should then use raw strings, eg. "open( r'c:\temp\somefile.txt' )".    The
IOError message gives a good clue, if you look closely (and remember that
'\t' == TAB character).

Also 'file' is the built-in file object in Python, so using it as a variable
is legal, but not a good practice.   In fact, using open() is somewhat
deprecated in favor of using file(), these days, although they both have the
same syntax.   So instead of this:

   for line in open( filename ):
       processLine( line )

It is now more common (I think) to do this:

   for line in file( filename ):
      processLine( line )

While these both accomplish the same task, the second is preferred, because
what you are doing it creating an instance of the file object (in both
cases) and iterating over it.    That means that the second is a little more
consistent and explicit, because the way to create some object in python is
normally through its constructor.   The file object just has this other way
of doing it (with 'open') for backward compatibility with the way it used to
be.

To reiterate the most salient point:

> Here's my example
> >>> file =open("c:\python23\programs\test.txt")

Your problem would be solved by adding a little 'r' in front of the filename
string, like so:

inputFile = file( r"c:\python23\programs\test.txt" )

(I also changed 'open' to 'file' and changed the variable name to avoid
stomping on the built-in 'file')

By the way, I think your second example works merely by luck, since '\t'
expands to the tab character, but '\T' does not.   I don't know whether the
fact that Python ignores invalid escape sequences (treating them as a
backslash followed by whatever the character is) is a feature or a bug.
Seems to me, if you didn't specify a raw string, but have invalid excape
sequences, an exception would be in order...





More information about the Python-list mailing list