Guess right case of path in Linux

Guess right case of path in Linux

In Linux your paths are case sensitive, if you have windows users who deal with case insensitive paths and want to communicate with them and handle their file requests you need to be able to "guess" which case is the correct one and return the file. This is a simple Python function to deal with such simple cases (fork it and use it on GitHub):

>>> guess_path_case('/TMP')
'/tmp'
>>> guess_path_case('/var/Log/DMESG')
'/var/log/dmesg'
>>> guess_path_case('/VAR/log/non-Existing/CaSe')
'/var/log/non-Existing/CaSe'
import os

def guess_path_case(path):
    path = os.path.normpath(path)
    items = []
    while path != '/':
        path, item = os.path.split(path)
        items.append(item)
    items.reverse()
    realpath = '/'
    for item in items:
        if os.path.exists(realpath):
            files = os.listdir(realpath)
        else:
            files = []
        for file in files:
            if item.lower() == file.lower():
                realpath = os.path.join(realpath, file)
                break
        else:
            # When path not found just attach item with unchanged case to the end
            realpath = os.path.join(realpath, item)
    return realpath