Python 2.7
create, rename, and delete files or directories
import os # Create a directory os.mkdir("/full/path/to/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("path", "directory", "filename") # Automatically uses "/" for linux/osx and "\" for windows # Get filename from path filename = os.path.basename("/full/path/to/file") # Move up directories path = os.path.dirname(os.path.abspath("/full/path")) # Add more os.path.dirname() to continue moving up # Check if a path exists if os.path.exists("/full/path"): # The path does exist # Check if a path is a directory if os.path.isdir("/full/path"): # The path is a directory
get a list of files in a directory
import os.path import glob paths = glob.glob(os.path.join("/full/path", "*"))
copy a single file
import shutil shutil.copy("/full/path/to/file", "/full/path/with/new/dir/or/name")
copy or delete entire directories
import shutil shutil.copytree("/full/path/to/dir", "/full/path/to/new/dir") # Use ignore=ignore_patterns("folder_name") to skip a dir shutil.rmtree("/full/path/to/dir")
create a file
f = open("/full/path/to/file.py", "w") f.write("print 'hello'\n") f.write("print 'world'") f.close()
run a file
execfile("/full/path/to/file.py")
get current user
import getpass user = getpass.getuser()
get os type
import os if os.name == "posix": # os is linux or osx elif os.name == "nt": # os is windows
using regular expressions
open a webpage
import webbrowser webbrowser.open("https://www.sarahvalstyne.com")
working with functions
def function_name(argument): # Do things here return result = function_name(None)
working with dictionaries
dictionary = {"key": "value"} for key in dictionary.keys(): value = dictionary[key] for key, value in dictionary.items(): pass
working with lists
a_list = ["a", "b", "c", 1, 2, 3] # Add a value to the end of a a_list a_list.append(value) # Add a value at a specific point in a a_list a_list.insert(index, value) # Remove the first item that matches the given value a_list.remove(value) # Remove the value at the given index a_list.pop(index) a_list.pop() # Removes the last value # Sort a a_list a_list.sort(reverse=False) # Count the number of items in a a_list count = len(a_list) # Get the min/max number min_value = min(a_list) max_value = max(a_list) # Remove duplicate values b_list = set(a_list)
working with strings
# Split parts = "string_001".split("_") name = parts[0] num = parts[1] # Split characters (works with lists as well) string = "string" string[:1] # Result: s string[1:] # Result: tring string[:-1] # Result: strin string[-1:] # Result: g # String replacements color = "yellow" num = 7 location = 4.287921 string = "%02d %s values at %.2f" % (num, color, location) # Result: 07 yellow values at 4.28 # String formatting string = "{color}.v{version}.exr".format(color="yellow", version=2) # Replace built-in string = "string_v001".replace("1", "2") # Result: string_v002
declare a raw string
string = r"string"
raw strings do not escape “"
force or convert a data type
string_ = str(x) float_ = float(x) integer_ = int(x) list_ = list(x) or [x] tuple_ = tuple(x) or [x] set_ = set(x) tup = (("a", 1) ,("b", 2), ("c", 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) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
iterating with range
for i in range(4): print i # Result: 0, 1, 2, 3 for i in range(4): i += 1 print i # Result: 1, 2, 3, 4
iterating with enumeration
letters = ["a", "b", "c"] for letter, count in enumerate(letters): print letter, count # Result: a 0, b 1, c 2