0
点赞
收藏
分享

微信扫一扫

整理照片,python批量修改名称


        最近在整理照片 , 但很多照片命名不规范。 如 SL373283.JPG , 实在比较难理解和排序。经过考虑,以照片产生时间(修改时间),作为命名方式,是个不错选择,修改后:2009-05-24-23-32-16-SL373283.JPG 。

        于是写了个脚本批量处理,以下供大家参考。

import os
import sys
import time

def check_dir_exit(file):
if os.path.isdir(file):
return 1
else:
print("File not exit:%s" %file)
return 0

def get_all_file_list(root, file_list, dir_list):

# os.walk() will be easy
dir_or_file = os.listdir(root)

for i in dir_or_file:
file_path = os.path.join(root, i)

if os.path.isdir(file_path):

dir_list.append(dir_list)

get_all_file_list(file_path, file_list, dir_list)
else:
file_list.append(file_path)

if __name__ == "__main__":
if len(sys.argv) < 2:
print("Command format error.")
exit(-1)
dir_name = sys.argv[1]
if 0 == check_dir_exit(dir_name) :
print("Failed...:%s" %dir_name)
exit(-1)
print("Begin to walk directory : %s" %dir_name)
print(time.ctime())
# begin real work

file_list = []
dir_list = []
get_all_file_list(dir_name, file_list, dir_list)

n = 1
for i in file_list:
bname = os.path.basename(i)
bdir = os.path.dirname(i)
if os.path.basename(i) == "Thumbs.db":
print("Ignore Thumbs.db")
continue

mtime = os.stat(i).st_mtime
file_modify_time = time.strftime('%Y-%m-%d-%H-%M-%S-', time.localtime(mtime))
o_name = i
n_name = bdir + os.sep + file_modify_time + bname
print("file%d : %s : %s, new name :%s" %(n, i, file_modify_time, n_name))
os.rename(i, n_name)

n += 1
print(time.ctime())


举报

相关推荐

0 条评论