Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check os.path.isfile(filename) with case sensitive in python

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.

like image 964
user1553605 Avatar asked Jun 24 '13 14:06

user1553605


People also ask

Are file paths case sensitive in Python?

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.

What does OS path Isfile do in Python?

path. isfile() method in Python is used to check whether the specified path is an existing regular file or not.


1 Answers

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
like image 64
Martijn Pieters Avatar answered Oct 14 '22 02:10

Martijn Pieters