2016-12-28

2016-12-26

Python - String replacement of anything between brackets or parenthesis (regex)

# [...]string_variable_name_here = "->[-asf asdf sd]<- br="">print re.sub( "\[(.*?)\]", "", string_variable_name_here )

# (...)string_variable_name_here = "->(-asf asdf sd)<- br="">print re.sub( "\((.*?)\)", "", string_variable_name_here )

2016-12-25

Python - Move all files of a given extension, to a target folder (search nested folder hierarchy)

import os, fnmatch, shutil

# InputssourceFolder = "/absolute_path_here/"targetFolder = "/absolute_path_here/"
# Create target directory if it doesn't existif not os.path.exists( targetFolder ): 
    os.makedirs( targetFolder )

# Traverse nested folder hierarchy, and move .txt files to given folderfor root, dirs, files in os.walk( sourceFolder ):
   for filename in fnmatch.filter( files, "*.txt" ):
      shutil.move( os.path.join(root, filename), os.path.join( targetFolder, filename ) )

Python - Find all zip files in nested folders, recursively, and unzip to a single given folder

import or, fnmatch, zipfile

ssourceFolder = "/entire_absolute_path_here/"targetUnzippedFolder = "/entire_absolute_path_here/"

for root, dirs, files in os.walk( sourceFolder ):
   for filename in fnmatch.filter( files, "*.zip" ):
      print "   " + os.path.join(root, filename)
      zipfile.ZipFile( os.path.join(root, filename) ).extractall( targetUnzippedFolder )

2016-12-21

Python - How to sort a multiple column list by column index number

import operator
sorted( list_name_here, key=operator.itemgetter(1,0) )

2016-12-18

Python - Traversing lists or data frames (xrange vs in)

# Method 1
# Requires knowing the length of the object to iterate over (n)
for i in xrange( 0, n ): action_code_here
# Method 2
# Does not require preemptively knowing the size of the traversed object
for i in list_or_dataFrame: action_code_here