Can you force os.path.isfile () to use case insensitivity when checking a file on the filesystem as case sensitive?

If I use os.path.isfile("foo.txt")

to validate a file named Foo.txt

, the function returns True

to the caseless file system and Windows. However, it returns False for case sensitive file systems. Is there a way to force case checking on isfile()

even on case sensitive file systems? I know there is a way to force case sensitivity for this feature on Windows, but what about another way?


I am working with DITA content. If you're developing DITA content on Windows and deploying your content to a case-sensitive Linux server, you could end up breaking links between topics if your href attributes have characters with a different case than the actual target files. I am trying to make a script that goes through every href attribute in our DITA source that is not an external link and updates it to match the real file. I can get the href attribute with the beautifulsoup module, but I'm having a hard time figuring out how to check and validate the actual filename so that I can use that line to update the href attribute in the DITA source.

A harder approach would be to just go through and convert each href and its target file to lowercase, but this can cause various problems if external sites have links to your content and they already have the right thing to do.

It is possible that the isfile () function is not the right tool for this task, but this is a start. I guess I could always run this script on Windows, but it's not very elegant. It would be better to have the script working properly on most systems.


source to share

1 answer

You can list all files in the parent directory and check the file names in a case insensitive manner:

import os

def getfile_insensitive(path):
    directory, filename = os.path.split(path)
    directory, filename = (directory or '.'), filename.lower()
    for f in os.listdir(directory):
        newpath = os.path.join(directory, f)
        if os.path.isfile(newpath) and f.lower() == filename:
            return newpath

def isfile_insensitive(path):
    return getfile_insensitive(path) is not None


The function isfile_insensitive

returns a boolean value indicating whether the parent directory has a file name that matches the name you are looking for in a case-insensitive manner.

The function getfile_insensitive

returns the path to an existing filename (with the correct case), so you can safely use that filename on your system.



All Articles