I need to check whether the given file is exist or not with case sensitive.
file = "C:\Temp\test.txt"
if os.path.isfile(file):
print "exist..."
else:
print "not found..."
TEST.TXT file is present under C:\Temp folder. but the script showing "file exist" output for file = "C:\Temp\test.txt", it should show "not found".
Thanks.
As some commenters have noted, Python doesn't really care about case in paths on case-insensitive filesystems, so none of the path comparison or manipulation functions will really do what you need.
path. isfile() method in Python is used to check whether the specified path is an existing regular file or not.
List all names in the directory instead, so you can do a case-sensitive match:
def isfile_casesensitive(path):
if not os.path.isfile(path): return False # exit early
directory, filename = os.path.split(path)
return filename in os.listdir(directory)
if isfile_casesensitive(file):
print "exist..."
else:
print "not found..."
Demo:
>>> import os
>>> file = os.path.join(os.environ('TMP'), 'test.txt')
>>> open(file, 'w') # touch
<open file 'C:\\...\\test.txt', mode 'w' at 0x00000000021951E0>
>>> os.path.isfile(path)
True
>>> os.path.isfile(path.upper())
True
>>> def isfile_casesensitive(path):
... if not os.path.isfile(path): return False # exit early
... directory, filename = os.path.split(path)
... return any(f == filename for f in os.listdir(directory))
...
>>> isfile_casesensitive(path)
True
>>> isfile_casesensitive(path.upper())
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With