Sunday, February 15, 2009

Useful System Commands (Part One)

Below I've compiled a sort of list/summary of some of the most common and useful "system" commands that I use quite frequently. This section deals mainly with directory/file manipulation and involves using 3 very powerful modules: os, sys, and glob.
import glob, os, sys

# List Files in a Directory
path = 'C:\\Users\\User\\Documents\\maya\\scripts'
files = os.listdir(path) # Returns Only fileNames
files = glob.glob(path) # Returns Full Path to fileNames

# Filter Files in a Directory
pythonScripts = glob.glob(path + '\\*.py')

# Split File Path by Path/Filename in One Go
path = 'C:\\Users\\User\\Documents\\maya\\scripts\\testScript.py'
filePath, fileName = os.path.split(path)

# Split Filename by Name/Extension in One Go
fileBaseName, fileExtension = os.path.splitext(fileName)

# Get Main User Documents Directory
os.path.expanduser('~') # Returns C:/Users/User/Documents
os.path.expanduser('~/maya/scripts') # Returns C:/Users/User/Documents/maya/scripts

# Check if File/Directory Exists, If Not Create it
if not os.path.isdir(path):
os.mkdir(path)
if not os.path.isfile(path):
print 'File Does Not Exist : %s' % path

# Rename Directory/File
os.rename(oldFilename, newFilename)

# Execute/Launch A File in it's Native Program
os.startfile(path)

# Check Python Enviornment Paths
pythonPaths = sys.path
sys.path.append( os.path.expanduser('~/maya/scripts/') )
Documentation:
- sys module
- os module
- glob module

No comments:

Post a Comment