Skip to content

Instantly share code, notes, and snippets.

@lincank
Created July 9, 2012 09:43
Show Gist options
  • Save lincank/3075375 to your computer and use it in GitHub Desktop.
Save lincank/3075375 to your computer and use it in GitHub Desktop.
make all files such as "dsf_kkk.jpg" into "kkk.jpg" in a specific folder
import os, re, sys
def sub_string(string, sub_str):
"""
Arguments:
- `string`: string you want to be truncated
- `sub_str`: starting sub-string (exclusive)
"""
index = string.rfind(sub_str)
if index > 0 and index < len(string):
return string[index + 1:]
else:
return string
def trim_cn(path):
regx = re.compile("\\.jpg", re.IGNORECASE)
name_list = filter (regx.search, os.listdir(path))
for i in range(len(name_list)):
name_list[i] = sub_string(name_list[i], "\\")
for item in name_list:
old = os.path.join(path, item)
new = os.path.join(path, sub_string(item, "_"))
os.rename(old, new)
def test_sub_string():
"""
"""
slash_list = ["fdsf\\1.txt", "fds\\2.rmb", "kkkk\\3.mp3"]
under_list = ["ff_1.txt", "fuiou_2.rmb", "mmm_3.mp3"]
ac_list = ["1.txt", "2.rmb", "3.mp3"]
for i in range(len(slash_list)):
if ac_list[i] == sub_string(slash_list[i], "\\"):
print "Test pass on: %s" % slash_list[i]
else:
print "Test FAIL!! on: %s" % slash_list[i]
if ac_list[i] == sub_string(under_list[i], "_"):
print "Test pass on: %s" % under_list[i]
else:
print "Test FAIL!! on: %s" % under_list[i]
def test():
"""
"""
path = "/tmp/trimtest/"
test_list = ["fdkf_1.jpg", "www_2.JPG"]
ac_list = ["1.jpg", "2.JPG"]
print "Generate list ..."
for i in range(len(test_list)):
f = open(os.path.join(path, test_list[i]), "w")
f.close()
trim_cn(path)
for i in range(len(ac_list)):
output = os.path.join(path, ac_list[i])
if os.path.exists(output):
print "Test pass on: %s" % ac_list[i]
os.remove(output)
else:
print "Test FAIL!! on: %s" % ac_list[i]
if len(sys.argv) == 2:
trim_cn(sys.argv[1])
else:
print "Take a path as arguement ..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment