Prettier code with the path module

By Filip Salomonsson; published on September 29, 2006.

Stop using os.path and start using Jason Orendorff's path module instead.

No, really. I mean right now.

Put down that sandwich, stop using os.path, and start using the path module instead!

The path module "provides a single class that wraps the functionality in the os.path module", and it does wonders with the readability of yor code.

Before:

import os.path
import glob

XML_DIR = "/long/damn/path/to/thousands/of/xmlfiles"
TXT_DIR = "/long/damn/path/to/thousands/of/txtfiles"

xmlfiles = glob.glob(os.path.join(XML_DIR, "*.xml"))
for xmlfile in xmlfiles:
    namebase, _ = os.path.splitext(os.path.basename(xmlfile))
    txtfile = open(os.path.join(TXT_DIR, namebase + ".txt"), "w")
    # ...

After:

from path import path

xmldir = path("/long/damn/path/to/thousands/of/xmlfiles")
txtdir = path("/long/damn/path/to/thousands/of/txtfiles")

for xmlfile in xmldir.files("*.xml")
    txtfile = open(txtdir / xmlfile.namebase + ".txt", "w")
    # ...

Addendum: I'm not sure what to think about the / operator for joining paths, but I'm quite certain I do like not having to say "os.path.whatever" or importing specific functions or going "glob glob" like I'm a thanksgiving turkey.