问题背景:用了半年时间录制了200集Python视频,内容结合了我系列教材《Python程序设计基础》、《Python程序设计(第2版)》和《Python可以这样学》(作者:董付国,清华大学出版社出版)三本书的大部分内容。现在视频录制差不多告一段落了,想整理一个清单。

在资源管理器里查看,视频文件名的格式如下图所示:

Python批量整理文件名小案例(附公众号第一批赠书活动中奖名单)_graphviz

现在想整理成下图所示的格式:

Python批量整理文件名小案例(附公众号第一批赠书活动中奖名单)_comet_02

根据以上的需求,写了下面的代码用来整理这些文件名:

import os
import re
path = r'D:\Python教学视频'
avis = [fn[:-4]\
        for fn in os.listdir(path)\
        if fn.endswith('.avi')]
def sort(item):
    '''首先按章节名字排序
然后按序号从小到大排序'''
    index = item.index(':')
    item = item[:index]
    # 查找文件名中的第一组数字,序号
    digits = re.findall(r'\d+', item)[0]
    # 返回值作为sort()方法的排序规则
    return (item[:item.index(digits)],\
            int(digits))
# 按指定规则进行排序
avis.sort(key=sort)
chapters = []
# 调整输出格式
for item in avis:
    # 文件名中第一组数字之前的是“章”的名字
    digits = re.findall(r'\d+', item)[0]
    index = item.index(digits)
    chapter = item[:index]
    if chapter not in chapters:
        chapters.append(chapter)
        print(chapter)
    # 文件名中冒号后面是“节”的名字
    print('\t', item[item.index(':')+1:])

--------------我是分割线-------------

“Python小屋”公众号

Python批量整理文件名小案例(附公众号第一批赠书活动中奖名单)_graphviz_03