You are here

Recursively create lowercase symlinks to filenames with uppercase letters - in Python

I'm working on a project to convert a big ASP website into Drupal. On Windows OSes there is not really a distinction between upper and lower case characters in filenames. At first I thought to just leave the capitals, but on web pages links were sometimes with capitals and sometimes lowercase. So I added some stuff to the Apache configuration, usually inside the VirtualHost directive (this does not work in .htaccess):

        RewriteEngine on
        RewriteMap lc int:tolower
        RewriteCond %{REQUEST_URI} [A-Z]
        RewriteRule (.*) ${lc:$1} [R=301,L]

But that wasn't all. For the project I'm parsing thousands of ASP files and the plan is to do this everyday while the existing website is updated. We're rsyncing files to be parsed, and the recursively rename to lowercase script I found is nice but it's not very efficient to copy and rename almost 3 GB everyday. I wrote a little Python script in the train today to create lowercase symbolic links to file and directory names with uppercase letters. The hardest part was to properly change directories - it's important to change into the directory the symlink is created but at the end of an os.walk it's necessary to get back to the current working directory.

I'm sure it can be useful to other people dealing with similar issues...

#!/usr/bin/env python

Recursively creates lower case symlinks to filenames with uppercase letters.

Created by Guaka in 2010, consider this public domain, copy and re-use freely.

import os

def lowlink(path = '.'):
    cwd = os.getcwd()  # os.walk can't handle path changes very well 
    for root, dirs, files in os.walk(path):
        # change directory for symlink creation
        os.chdir(os.path.join(cwd, root))
        print root
        for name in files + dirs:
            lowname = name.lower()
            if name != lowname and not os.path.exists(lowname):
                os.symlink(name, lowname)
        os.chdir(cwd) # restore path for os.walk

my working setup