一个整理文件的python脚本

最后由 Janis 更新于 2022年9月25日

近日由于需要整理从各处下载来的pixiv/fanbox图片,痴呆笔者写了如下脚本。

需要整理的文件结构为:父目录-一大堆以画师命名的文件夹-图片标题文件夹-图片.jpg&说明.txt&etc.,需求是把所有子目录中的图片和视频递归提取,存储到画师名文件夹里

首先在根目录运行DIR *.* /B > list.txt获取根目录下所有画师名文件夹的list

由于弱智作者不知道怎么处理py编码,需要将list.txt转换为UTF-8编码,删除不兼容的字符并同步修改文件夹名称

把1.py、list.txt和“画师1”(即父目录)放在同一个目录下即可使用,整理好的会复制到“画师”文件夹

有若干种文件命名方法,这里为了可维护性选择用毫秒级时间戳,这样之后下载的其他图片也会被按时间排序,考虑到windows智慧文件名称排序

顺带一提AllDup去除重复文件很好用

import os,shutil,zlib,datetime,time

def crc32(file_path):
#计算文件 crc32 hash 值
    with open(file_path, 'rb') as fh:
        hash = 0
        while True:
            s = fh.read(65536)
            if not s:
                break
            hash = zlib.crc32(s, hash)
        return "%08X" % (hash & 0xFFFFFFFF)

def move(k):
    source_path = os.path.join("画师1", k)
    target_path = os.path.join("画师", k)

    if not os.path.exists(target_path):
        os.makedirs(target_path)

    if os.path.exists(source_path):
        #编号命名的计数器
        i = 0
        for root, dirs, files in os.walk(source_path):
            for file in files:
                #编号命名
                #num_str=str(i+1).zfill(6)
                if file.endswith((".png",".jpg",".jpeg","mp4", "mkv")):
                    src_file = os.path.join(root, file)
                    #时间戳命名
                    #now_time = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
                    #CRC32命名
                    #crc = crc32(src_file)
                    #另一种时间戳命名
                    time_stamp = int( round(time.time() * 1000) ) 
                    #这里有个bug就是文件名里不能有'.'
                    name =  str(time_stamp) + "." + file.split('.')[1]
                    target_path = os.path.join(target_path, name)
                    shutil.copy(src_file, target_path)
                    target_path = os.path.join("画师", k)
                    i = i + 1

folders = open('list.txt',"rb")
for i in folders.readlines():
    move(i.strip().decode())
    print(i.strip().decode())

Visits: 13

发布者:Janis

,,,

留下评论

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据