views:

34

answers:

3

I know that the file name is file001.txt or FILE001.TXT, but I don't know which. The file is located on a Windows machine that I'm accessing via samba mount point.

The functions in os.path seem to be acting as though they were case-insensitive, but the open function seems to be case-sensitive:

>>> from os.path import exists, isfile

>>> exists('FILE001.TXT')
True

>>> isfile('FILE001.TXT')
True

>>> open('FILE001.TXT')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'FILE001.TXT'

>>> open('file001.txt')    # no problem

So, my questions are these:

  1. Is there a way to determine what the file name is without opening the file (or listing the directory that it's in)?

  2. Why is open case-sensitive when os.path isn't?


Update: thanks for the answers, but this isn't a python problem so I'm closing the question.

A: 

To answer your questions:

  1. You can use stat to determine wether a file exists or not without attempting to open it.
  2. Windows Shares filesystems are not case sensitives.
Pablo Santa Cruz
`stat` works (so does getctime and everything else I've tried except `open`).
Seth
A: 
def exists(path):
    try:
        open(path).close()
    except IOError:
        return False
    return True

Permission issues aside, why don't you want to open the file?

Nick Presta
It's not that I don't want to open the file, but that I need the correct file name for opening later.
Seth
A: 

You might try adding nocase to the mount in your fstab, as in the example I dug up below if it isn't already there:

//server/acme/app    /home/joe/.wine/drive_c/App    cifs    guest,rw,iocharset=utf8,nocase,file_mode=0777,dir_mode=0777    0    0

Found a link explaining normcase

normcase is a useful little function that compensates for case-insensitive operating systems that think that mahadeva.mp3 and mahadeva.MP3 are the same file. For instance, on Windows and Mac OS, normcase will convert the entire filename to lowercase; on UNIX-compatible systems, it will return the filename unchanged.

That tells you that open is probably always expecting a lower case filename on Windows filesystems.

As such, the reason os.path isn't case sensitive is that it probably calls os.path.normcase before checking for the file, while open does not. Though, that might also just be a bug.

mootinator
I was hopeful for this suggestion, but `nocase` doesn't change the behavior. FILE001.TXT and file001.txt both return true in `os.path.exists`.
Seth
@Seth Does os.path.normcase(file) return the filename with the correct case? You'll have to excuse me if that's a naive question I haven't touched python itself in awhile.
mootinator