Skip to content

Instantly share code, notes, and snippets.

@lincank
Created July 9, 2012 09:38
Show Gist options
  • Save lincank/3075362 to your computer and use it in GitHub Desktop.
Save lincank/3075362 to your computer and use it in GitHub Desktop.
Give unique names for each picture
import os, sys, pprint, re, shutil, random
log_file = "/tmp/batch-rename.log"
f = open(log_file, 'w')
regx = re.compile("\\.jpg|\\.png|\\.gif", re.IGNORECASE)
def subdirs(path):
"""
Return a dict in this format: {"path", [basenames of files in this path]}
Arguments:
- `path`: path to start search
"""
rename_dict ={}
# for file filter
# os.walk returns (path, dir_list, file_list)
for i in os.walk(path):
if i[2]:
fileList = []
# only get those picture files
rename_dict[i[0]] = filter(regx.search, i[2])
return rename_dict
def batch_rename(path, target=None):
"""
search particular type of files in path and move them to target directory
with unique name
Arguments:
- `path`:
"""
rename_dict = subdirs(path)
# create directory if it doesn't exist for file write
if (target is not None) and (not os.path.exists(target)):
os.mkdir(target)
# ensure uniqueness
counter = 0
for path, nameList in rename_dict.items():
# logging
progress = "Processing: %s \n" % path
print progress
f.write(progress)
counter += 1
dist = path if target is None else target
for file_name in nameList:
old_name = os.path.join(path, file_name)
new_name = os.path.join(dist, "%s_%s" % (counter, file_name))
os.rename(old_name, new_name)
# loggging
f.write("moving: %s to %s \n" % (old_name, new_name))
f.close()
print "Log location: ", log_file
def clear_dirs(dir_list):
"""
"""
for path_dir in dir_list:
if os.path.exists(path_dir):
shutil.rmtree(path_dir)
def test():
"""
"""
rand = random.randrange(1, 100000)
in_dir = "/tmp/batch_rename_in_%s" % rand
sub_dir = os.path.join(in_dir, "sub")
out_dir = "/tmp/batch_rename_out_%s" % rand
dir_dict = {in_dir: ["1.jpg", "2.JPG", "3.mp3", "23jpg", "3.vps"],
sub_dir: ["6.jpg", "8.JPG", "9.go"]}
clear_dirs([in_dir, out_dir])
for path_dir in [in_dir, sub_dir, out_dir]:
os.mkdir(path_dir)
print "Generating files ...\n"
for path_dir, name_list in dir_dict.items():
for file_name in name_list:
f = open(os.path.join(path_dir, file_name), "w")
f.close()
print "in: %s, out: %s\n" % (in_dir, out_dir)
batch_rename(in_dir, out_dir)
print "Testing result: \n"
for path_dir, name_list in dir_dict.items():
counter_range = [1, 2]
for file_name in filter(regx.search, name_list):
output1 = os.path.join(out_dir, "1_%s" % ( file_name))
output2 = os.path.join(out_dir, "2_%s" % ( file_name))
if os.path.exists(output1) or os.path.exists(output2):
print "Match: %s" % file_name
else:
print "Test fail at: %s" % file_name
clear_dirs([in_dir, out_dir])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment