views:

288

answers:

4

Though Windows is case insensitive, it does preserve case in filenames. In Python, is there any way to get a filename with case as it is stored on the file system?

E.g., in a Python program I have filename = "texas.txt", but want to know that it's actually stored "TEXAS.txt" on the file system, even if this is inconsequential for various file operations.

+1  A: 
>>> import os
>>> os.listdir("./")
['FiLeNaMe.txt']

Does this answer your question?

sberry2A
+1  A: 

You could use:

import os
a = os.listdir('mydirpath')
b = [f.lower() for f in a]
try:
    i = b.index('texas.txt')
    print a[i]
except ValueError:
    print('File not found in this directory')

This of course assumes that your search string 'texas.txt' is in lowercase. If it isn't you'll have to convert it to lowercase first.

Chinmay Kanchi
`print ([f for f in os.listdir("mydirpath") if f.lower() == "texas.txt"]+["file not found"])[0]`
Roger Pate
@Roger: Haha, great stuff! I'm still getting to grips with the power of list comprehensions. I tend not to post one-liners for answers though, since they can often be more confusing than illuminating :).
Chinmay Kanchi
Just a note: No need to use string.lower() anymore.
ghostdog74
@ghostdog74: Fixed.
Chinmay Kanchi
The `except` block functionally does nothing -- thus ignoring errors silently.
Sridhar Ratnakumar
I don't think he's looking for the "texas" file per se ...
hasen j
@Sridhar: what?
Chinmay Kanchi
@Chinmay: look closely at the statements in your `except` block (i.e, the last line of your program). It does **nothing**.
Sridhar Ratnakumar
Oops... Fixed now.
Chinmay Kanchi
+1  A: 

and if you want to recurse directories

import os
path=os.path.join("c:\\","path")
for r,d,f in os.walk(path):
    for file in f:
        if file.lower() == "texas.txt":
              print "Found: ",os.path.join( r , file )
ghostdog74
+4  A: 

Here's the simplest way to do it:

>>> import win32api
>>> win32api.GetLongPathName(win32api.GetShortPathName('texas.txt')))
'TEXAS.txt'
Sridhar Ratnakumar
This didn't work for me - I still get 'texas.txt'.
diggums
Does `win32api.GetLongPathName(win32api.GetShortPathName('texas.txt'))` work?
Sridhar Ratnakumar
Yes, that works. Actually, to clarify, your original suggestion does work, but not if including a directory - e.g., `win32api.GetLongPathName('\\states\\texas.txt')` yields `'\\states\\TEXAS.txt'`, whereas `win32api.GetLongPathName(win32api.GetShortPathName('\\states\\texas.txt'))` correctly yields `'\\STATES\\TEXAS.txt'`. That had confused me, now I'm all set. Thanks!
diggums
I see. Then, I have modified my answer to call `win32api.GetShortPathName` as well.
Sridhar Ratnakumar