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-inse开发者_如何转开发nsitive, 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:
Is there a way to determine what the file name is without opening the file (or listing the directory that it's in)?
Why is
open
case-sensitive whenos.path
isn't?
Update: thanks for the answers, but this isn't a python problem so I'm closing the question.
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.
To answer your questions:
- You can use
stat
to determine wether a file exists or not without attempting to open it. - Windows Shares filesystems are not case sensitives.
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?
精彩评论