我需要检查给定文件是否存在,区分大小写。
file = "C:\Temp\test.txt"
if os.path.isfile(file):
print "exist..."
else:
print "not found..."
TEST.TXT文件存在于C:\ Temp文件夹下。但是脚本显示“file exists”输出为file =“C:\ Temp \ test.txt”,它应显示“未找到”。
感谢。
答案 0 :(得分:13)
列出目录中的所有名称,以便进行区分大小写的匹配:
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..."
演示:
>>> 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
答案 1 :(得分:-2)
os.path.isfile在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