create, rename, and delete files or directories
import os
# create a directory
os.mkdir("full/path/to/new/directory")
# rename a file or directory
os.rename("full/path/to/file", "full/path/with/new/name")
# delete a file or directory
os.remove("full/path/to/file")
working with file paths
import os.path
# combine paths
path = os.path.join("first/path", "second/path/or/name")
# automatically uses "/" for linux/osx and "\" for windows
# separate file name from a full path
name = os.path.basename("full/path/with/file")
# move up directories
path = os.path.dirname(os.path.abspath("full/path"))
# this would move up a single directory
# to move up multiple, add more os.path.dirname()
# check if a path exists
if os.path.exists("full/path/to/test"):
print "path exists"
else:
print "path does not exist"
# check if a path is a directory
if os.path.isdir("full/path/to/test"):
print "path is a directory"
else:
print "path is a file"
get a list of files in a directory
import os.path, glob
globPatt = os.path.join("full/path/to/files", "*")
paths = glob.glob(globPatt)
paths.sort()
for path in paths:
name = os.path.basename(path)
copy a single file
import shutil
# copy to the same directory with new name
shutil.copy('full/path/file_v1.txt', 'full/path/file_v2.txt')
# copy to a new directory with the same name
shutil.copy('full/path/file.txt', 'new/path/file.txt')
copy or delete entire directories
import shutil
shutil.copytree('full/path/to/folder', 'full/path/to/new/dst')
# use ignore=ignore_patterns('folderName') to skip a dir
shutil.rmtree('full/path/to/folder')
get current user
import getpass
user = getpass.getuser()
determine os type
import os
if os.name == "posix":
# os is linux or mac osx
elif os.name == "nt":
# os is windows
using regular expressions
import re
# example 1: find a number in a string
file_name = "example_0001.exr"
pattern = re.compile("(\w+)[._](\d+)[._](exr|jpg)")
info = re.search(pattern, file_name))
num = info.group(2)
print num ## Result = 0001
# example 2: check if a string matches a pattern
light_name = "arnold_01_light"
pattern = re.compile(r"arnold_(\d)(\d)_light")
if re.match(pattern, light_name):
print "yes"
note, the pattern should be changed based on the situation more information
open a webpage
import webbrowser
webbrowser.open('https://www.sarahvalstyne.com')
working with functions
def functionName(*args):
name = 'test'
num = 1
return name, num
name, num = functionName()
create a file
f = open('full/path/to/new/file.py', 'w')
f.write("print 'hello'\n")
f.write("print 'world'")
f.close()
run a file
execfile('full/path/to/file.py')
iterating through dictionaries
dictionary = {"key":"value"}
# option 1
for key in dictionary:
print key, dictionary[key] # prints key and value
# option 2
for key, value in dictionary.iteritems():
print key, value
dictionary = {"key":["value1", "value2"]}
# option 1
for key in dictionary:
for value in dictionary[key]:
print key, value
# option 2
for key, list in dictionary.iteritems():
for value in list:
print key, value
working with lists
# add a value to the end of a list
list.append(value)
# add a value at a specific point in a list
list.insert(0, value) # inserts at front of list
# remove the first item that is equal to the given value
list.remove(value)
# remove the value at the given position
list.pop(0) # removes the first value
list.pop() # removes the last value
# sort the values in a list
list.sort(reverse=False)
# count the number of items in a list
num = len(list)
# get the min/max number in a list of numbers
num_list = [1, 2, 3]
min = min(num_list)
max = max(num_list)
remove duplicate values from lists/tuples
list = [1, 1, 2, 2]
print set(list)
# result: {1, 2}
working with strings
# split
string = 'test_0001'
parts = string.split('_')
name = parts[0]
num = parts[1]
# split characters
string = 'parker'
string[:1] # result: p
string[1:] # result: arker
string[:-1] # result: parke
string[-1:] # result: r
# replace method 1 (with precision)
color = 'yellow'
num = 7
local = 4.287921
string = '%02d %s values at %.2f' % (num, color, local)
# result: 07 yellow values at 4.28
# replace method 2
string = 'test_v1'
string = string.replace('1', '2')
# result: test_v2
declare a raw string
string = r"string"
raw strings treat \ as a character instead of an escape character
force/convert data type
string = str(x)
float = float(x)
integer = int(x)
list = list(x)
tuple = tuple(x)
set = set(x)
tup = (('a', 1) ,('f', 2), ('g', 3))
dictionary = dict(tup)
get character lists
import string
lowercase = list(string.ascii_lowercase)
# abcdefghijklmnopqrstuvwxyz
uppercase = list(string.ascii_uppercase)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
digits = list(string.ascii_digits)
# 0123456789
punctuation = list(string.ascii_punctuation)
# !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
get a list of numbers from a range
start, end = [0, 10]
num_list = list(range(start, end+1))
print num_list
# result: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
get a list of numbers from a string of numbers/ranges, separated by ','
string = '1, 4-7, 10' # input string
num_list = []
if string != '':
string = string.replace(' ', '')
string_parts = string.split(',')
for part in string_parts:
if '-' in part:
parts = part.split('-')
start = int(parts[0])
end = int(parts[1]) + 1
for i in range(start, end):
num = '%02d' % i # optional precision
num_list.append(num)
else:
num = '%02d' % int(part) # optional precision
num_list.append(num)
print num_list
# result: 01, 04, 05, 06, 07, 10
calculate tire rotation (with distance traveled & tire radius)
import math
distance = ##
radius = ##
rotations = distance / (2 * math.pi * radius)
degrees = rotations * 360
print '%.3f rotations' % rotations
print '%.3f degrees' % degrees