Check os.path.isfile (file name) case sensitive in python

I need to check if this file exists or not case sensitive.

file = "C:\Temp\test.txt" if os.path.isfile(file): print "exist..." else: print "not found..." 

The TEST.TXT file is present in the C: \ Temp folder. but the script shows "file exists" for file = "C: \ Temp \ test.txt", it should show "not found".

Thanks.

+8
python windows
source share
2 answers

Instead, list all the names in the directory so that you can be case-sensitive:

 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 
+13
source share

os.path.isfile is not case sensitive in python 2.7 for windows

 >>> os.path.isfile('C:\Temp\test.txt') True >>> os.path.isfile('C:\Temp\Test.txt') True >>> os.path.isfile('C:\Temp\TEST.txt') True 
-3
source share

All Articles