Created
March 14, 2013 15:58
-
-
Save ameliaikeda/5162563 to your computer and use it in GitHub Desktop.
I was given an hour to mass-rename 100k files in various folders. challenge accepted. (and the script took 5 minutes)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import MySQLdb | |
import re | |
class ImageSorter(object): | |
def __init__(self, base_directory): | |
self.cur = MySQLdb.connect(host='127.0.0.1', user="root", db="magento").cursor() # come at me | |
self.skus = {} | |
self.directory = base_directory | |
self.counter = 0 | |
def fetch_sku(self): | |
self.cur.execute("SELECT product_id, SKU FROM icon_info") | |
rows = self.cur.fetchall() | |
for row in rows: | |
#print "({},{})".format(row[0], row[1]) | |
self.skus[int(row[0])] = row[1] | |
def sku_match(self, filename): | |
for id, sku in self.skus.iteritems(): | |
if str(sku) in filename: | |
#print id | |
return [id, sku] | |
return [] | |
def rename(self, sku, filename, id): | |
#print isinstance(sku, str) | |
new = filename.replace(sku, "WS-{}".format(id)) | |
#print "Renaming. Filename={}, ID={}, New={}, SKU={}".format(filename, id, new[0], self.skus[id]) | |
os.rename(str(filename), str(new)) | |
def run(self): | |
self.fetch_sku() | |
for root, dirs, files in os.walk(self.directory): | |
for filename in files: | |
self.counter = self.counter + 1 | |
if self.counter % 2000 == 0: # pregress report | |
print "Status {}: {}".format(self.counter, filename) | |
test = self.sku_match(filename) | |
if test: | |
try: | |
self.rename(test[1], os.path.join(root, filename), test[0]) | |
except WindowsError: | |
print "Error: {}:{}".format(test, filename) | |
if __name__ == '__main__': | |
i = ImageSorter(os.getcwd()) | |
i.run() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment