我需要检查给定的文件是否存在,并且要区分大小写。
file = "C:\Temp\test.txt"
if os.path.isfile(file):
print "exist..."
else:
print "not found..."
C:\Temp文件夹下存在TEST.TXT文件。但是脚本显示的是对于文件="C:\Temp\test.txt" 的"file exist"输出,实际上应该显示"not found"。
谢谢。
我需要检查给定的文件是否存在,并且要区分大小写。
file = "C:\Temp\test.txt"
if os.path.isfile(file):
print "exist..."
else:
print "not found..."
C:\Temp文件夹下存在TEST.TXT文件。但是脚本显示的是对于文件="C:\Temp\test.txt" 的"file exist"输出,实际上应该显示"not found"。
谢谢。
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
any()
是第一版的遗留问题,当时我回答了相反的问题(即完全错误)。当然,为什么OP想要这个有点神秘。 - Martijn PietersTEST.TXT
文件,test.txt
目录),针对三种可能的不区分大小写输入(文件的确切大小写匹配、目录的确切大小写匹配以及第三种是对两者进行不区分大小写匹配但不匹配大小写的情况),os.path.isfile()
会做什么? - Martijn PietersText
和TEXT
和text
和tExT
等,在大多数Windows文件系统上都是相同的文件名(NTFS在底层是不区分大小写的,但Windows操作系统在其上添加了一个区分大小写的层)。 - Martijn Pieters在Windows下,Python 2.7中的os.path.isfile不区分大小写。
>>> os.path.isfile('C:\Temp\test.txt')
True
>>> os.path.isfile('C:\Temp\Test.txt')
True
>>> os.path.isfile('C:\Temp\TEST.txt')
True
file
匹配c:\Temp\TEST.TXT
,还是 不要 匹配它? - MattDMoC:\Temp\test.txt
和C:\Temp\TEST.TXT
是完全相同的,因此通过isfile
得到的结果是正确的。 - Bakuriuos.listdir()
是区分大小写的,尽管... - MattDMoC:\Temp\test.txt
和C:\Temp\TEST.TXT
是完全相同的。但在Linux/Unix系统上,文件系统区分大小写,这个特性并不适用于Python。换句话说,这是在不同平台上实现os.*
库函数的差异,而不是Python的特性。 - twalbergos
实现以便您不必更改适用于不同操作系统的代码。顺便说一句:如果你想在Windows上使用posix的路径模块,可以这样做:import posixpath
然后使用posixpath.isfile
而不是os.path.isfile
(虽然我不确定这是否适用于此特定情况)。 - Bakuriu