在python中检查区分大小写的os.path.isfile(filename)

use*_*605 10 python windows python-2.7

我需要检查给定文件是否存在,区分大小写.

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

TEST.TXT文件存在于C:\ Temp文件夹下.但是显示"file exists"输出的脚本为file ="C:\ Temp\test.txt",它应显示"未找到".

谢谢.

Mar*_*ers 14

列出目录中的所有名称,以便您可以进行区分大小写的匹配:

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..."
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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
Run Code Online (Sandbox Code Playgroud)