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

Posted

技术标签:

【中文标题】在 python 中检查 os.path.isfile(filename) 是不是区分大小写【英文标题】:check os.path.isfile(filename) with case sensitive in python在 python 中检查 os.path.isfile(filename) 是否区分大小写 【发布时间】:2013-06-21 01:59:54 【问题描述】:

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

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

TEST.TXT 文件位于 C:\Temp 文件夹下。但显示文件 =“C:\Temp\test.txt”的“文件存在”输出的脚本应该显示“未找到”。

谢谢。

【问题讨论】:

澄清一下,你想让file匹配c:\Temp\TEST.TXT,还是匹配它? 你想要的是反对操作系统。在 python 中,C:\Temp\test.txtC:\Temp\TEST.TXT 完全相同 相同,因此您通过 isfile 得到的结果是正确的。 (因为Windows文件系统不区分大小写) os.listdir() 区分大小写,不过... @Bakuriu 澄清一点,在 Python 中,在具有不区分大小写的文件系统(或其他此类系统)的 Windows 系统上,C:\Temp\test.txtC:\Temp\TEST.TXT 完全相同。这在 Linux/Unix 上的 Python 中并不成立,其中文件系统区分大小写。换句话说,这是 os.* 库例程在不同平台上实现的差异——不是专门的 Python 特性。 【参考方案1】:

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

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

【讨论】:

return filename in os.listdir(directory) 1. 如果同时存在 TEST.TXT 文件和 test.txt 目录,它会失败(以及 any() 代码)(是否可以通过编程方式在 ntfs 卷上创建它们? ) 2. 在不区分大小写、破坏大小写的情况下(某些网络方案)可能会失败。 @J.F.Sebastian:确实; any() 是第一个版本的保留,我回答了反问题(即完全弄错了)。为什么 OP 想要这个当然有点神秘。 @JFSebastian:对于 NTFS 上的大小写匹配目录加精确相同大小写更改文件名情况(所以TEST.TXT 文件,test.txt 目录),@987654328 @ 为三个可能的不区分大小写的输入(文件、目录的精确区分大小写匹配,第三个是不区分大小写但不匹配大小写的匹配)? 我的猜测——这是一种未定义的行为。 借助此解决方案进行检查是可能的并且一切正常。但是,创建两个具有相同字符序列的文件不是 - 不是在 Windows 上!如果在创建“test.txt”之前存在“Test.txt”,则可以将后缀附加到“test.txt”,反之亦然以创建这两个文件——因为它是必要的,例如,为大小写导出字典条目——敏感语言(如德语:“Abendessen”(名词)与“abendessen”(动词))【参考方案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

【讨论】:

不,太多的干扰,你是对的。然而,这不是答案; OP 正在询问如何进行大小写 sensitive 测试。

以上是关于在 python 中检查 os.path.isfile(filename) 是不是区分大小写的主要内容,如果未能解决你的问题,请参考以下文章

在 Python 中检查 Linux 上的 USB 驱动器?

在 Python 中,如何检查字符串是不是只包含某些字符?

如何在 Python 中检查字符串中是不是包含数值? [复制]

在python中检查文件属性

Python - 检查字母是不是出现在连续的单词中

python - 如何在python中使用IF语句检查两个列表的元素是不是相等?