Welcome, guest | Sign In | My Account | Store | Cart

Python provides good utilities for transforming filenames, but they are tedious to use and clutter up the source code.

FileSpec offers one-stop shopping to convert a file path to every component you might want to know, reuse, or transform.

Python, 22 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class FileSpec(object):
    def __init__(self, path):
        self.drive, self.path_minus_drive = os.path.splitdrive(path)
        self.dir, self.name = os.path.split(path)
        self.corename, self.ext = os.path.splitext(self.name)
        self.ext = self.ext.lower()
        self.dir_minus_drive = self.dir[2:]        

    def substitute_drive(self, drive):
        return os.path.join(drive, os.sep, self.path_minus_drive)
        
    def substitute_dir(self, dir_):
        return os.path.join(dir_, self.name)
        
    def substitute_name(self, name):
        return os.path.join(self.dir, name)
        
    def substitute_corename(self, corename):
        return os.path.join(self.dir, corename + self.ext)
        
    def substitute_ext(self, ext):
        return os.path.join(self.dir, self.corename + ext)

There's nothing deep or magical about this code snippet, but I reuse it all the time. I often convert files or rename them in some fashion. Python gives me everything I need to accomplish such tasks; however, it's always tedious.

Now I create a FileSpec for a path in one line of code. Then quickly and simply I create a new path in a second line without thinking about splitting this, then joining that.