Lor*_*ein 15 python filesystems ntfs hfs+
如果文件系统不区分大小写,是否有一种简单的方法来检查Python?我正在考虑像HFS +(OSX)和NTFS(Windows)这样的文件系统,你可以在其中访问与foo,Foo或FOO相同的文件,即使保留了文件大小写.
Amb*_*ber 18
import os
import tempfile
# By default mkstemp() creates a file with
# a name that begins with 'tmp' (lowercase)
tmphandle, tmppath = tempfile.mkstemp()
if os.path.exists(tmppath.upper()):
# Case insensitive.
else:
# Case sensitive.
Run Code Online (Sandbox Code Playgroud)
除非明确处理关闭和删除,否则Amber提供的答案将留下临时文件碎片.为避免这种情况,我使用:
import os
import tempfile
def is_fs_case_sensitive():
#
# Force case with the prefix
#
with tempfile.NamedTemporaryFile(prefix='TmP') as tmp_file:
return(not os.path.exists(tmp_file.name.lower()))
Run Code Online (Sandbox Code Playgroud)
虽然我的使用案例通常不止一次地测试这个,所以我存储结果以避免不止一次触摸文件系统.
def is_fs_case_sensitive():
if not hasattr(is_fs_case_sensitive, 'case_sensitive'):
with tempfile.NamedTemporaryFile(prefix='TmP') as tmp_file:
setattr(is_fs_case_sensitive,
'case_sensitive',
not os.path.exists(tmp_file.name.lower()))
return(is_fs_case_sensitive.case_sensitive)
Run Code Online (Sandbox Code Playgroud)
如果仅调用一次,则速度稍慢,而在其他情况下调整速度要快得多.