Building up Python Lego pieces – some directory stuff


I lost all my Python code that I have written and collected over time, don’t ask why. So I am in the process of building that back up. Here is some code to create directories for a SQL Server gig I am working on.

Highlights:
1. Use os.path.join to take care of the forward and backward slashes on different operating systems. Somewhat similar to shlex module that take care of escaping. I’ve tested this successfully on both Windows and Linux;
2. Notice os.makedirs can make a directory and one of its sub-directories in one go.

[sourcecode language=”Python”]
import os

if not os.path.isdir(os.path.join(“c:/”, “storage”, “data”)):
os.makedirs(os.path.join(“c:/”, “storage”, “data”))

if not os.path.isdir(os.path.join(“c:/”, “storage”, “log”)):
os.makedirs(os.path.join(“c:/”, “storage”, “log”))

for i in [1,2,3,4,5,6]:
for j in [1,2,3,4]:
for k in [0,1]:
if not os.path.isdir(os.path.join(“c:/”, “storage”, “data”, “%s_%s_%s” % (i, j, k))):
os.makedirs(os.path.join(“c:/”, “storage”, “data”, “%s_%s_%s” % (i,j, k)))
if not os.path.isdir(os.path.join(“c:/”, “storage”, “log”, “%s_5_0” % i)):
os.makedirs(os.path.join(“c:/”, “storage”, “log”, “%s_5_0” % i))

if not os.path.isdir(os.path.join(“c:/”, “FastTrack Labs”, “Lab 2”, “Exercise 2”, “Output”)):
os.makedirs(os.path.join(“c:/”, “FastTrack Labs”, “Lab 2”, “Exercise 2”, “Output”))
[/sourcecode]

,

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.