检查 os.path.isfile(filename) 在 python 中区分大小写 [英] check os.path.isfile(filename) with case sensitive in python
本文介绍了检查 os.path.isfile(filename) 在 python 中区分大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要检查给定的文件是否存在,区分大小写.
file = "C:\Temp\test.txt"如果 os.path.isfile(file):打印存在..."别的:打印未找到..."
TEST.TXT 文件位于 C:\Temp 文件夹下.但是显示 file = "C:\Temp\test.txt" 的 "file exists" 输出的脚本,它应该显示 "not found".
谢谢.
解决方案
改为列出目录中的所有名称,以便您可以进行区分大小写的匹配:
def isfile_casesensitive(path):如果不是 os.path.isfile(path): return False # 提前退出目录,文件名 = os.path.split(path)在 os.listdir(directory) 中返回文件名如果 isfile_casesensitive(file):打印存在..."别的:打印未找到..."
演示:
<预><代码>>>>导入操作系统>>>file = os.path.join(os.environ('TMP'), 'test.txt')>>>打开(文件,'w')# 触摸<打开文件'C:\\...\\test.txt',模式'w'在0x00000000021951E0>>>>os.path.isfile(路径)真的>>>os.path.isfile(path.upper())真的>>>def isfile_casesensitive(path):... 如果不是 os.path.isfile(path): return False # 提前退出... 目录,文件名 = os.path.split(path)... return any(f == filename for f in os.listdir(directory))...>>>isfile_casesensitive(path)真的>>>isfile_casesensitive(path.upper())错误的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.
解决方案
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
这篇关于检查 os.path.isfile(filename) 在 python 中区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文