Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file system is case-insensitive in Python

Is there a simple way to check in Python if a file system is case insensitive? I'm thinking in particular of file systems like HFS+ (OSX) and NTFS (Windows), where you can access the same file as foo, Foo or FOO, even though the file case is preserved.

like image 674
Lorin Hochstein Avatar asked Oct 23 '11 23:10

Lorin Hochstein


People also ask

How do you make a check case-insensitive in Python?

Approach No 1: Python String lower() Method This is the most popular approach to case-insensitive string comparisons in Python. The lower() method converts all the characters in a string to the lowercase, making it easier to compare two strings.

Are file paths case-sensitive in Python?

Paths are case sensitive even on Windows, which is case insensitive · Issue #69 · jmcgeheeiv/pyfakefs · GitHub.

Which file system has case insensitivity?

Linux file system treats file and directory names as case-sensitive.

Are file paths case-sensitive?

Yes. Windows (local) file systems, including NTFS, as well as FAT and variants, are case insensitive (normally).


2 Answers

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.
like image 158
Amber Avatar answered Oct 27 '22 00:10

Amber


The answer provided by Amber will leave temporary file debris unless closing and deleting are handled explicitly. To avoid this I use:

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()))

Though my usage cases generally test this more than once, so I stash the result to avoid having to touch the filesystem more than once.

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)

Which is marginally slower if only called once, and significantly faster in every other case.

like image 36
Steve Cohen Avatar answered Oct 27 '22 00:10

Steve Cohen