栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

整理照片,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())

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/725993.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号