批量重命名文件-py
本文最后更新于 1546 天前,其中的信息可能已经有所发展或是发生改变。
# 多行输出结果
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

文件批量重命名

重命名选定目录下所有文件,只命令同一格式的文件。
说明:

  1. 重命名的规则为在输入的文件名后追加序号, 默认为文件夹的名字;
  2. 可设置起始序号自定义, 如从 4 开始;
  3. 可指定文件格式,默认为第一个文件的格式。

注意: 重命名后不能还原, 故推荐先预览结果再重命名。

import os

path = 'E:/S.A.O/S.A.O. season-2'

# default file name
namePattern = os.path.split(path)[1] + ' '
# start num
st = 15

fileNames = list(os.walk(path))[0][2]
fileNames.sort(key=len)
fileNums = len(fileNames)
# default file extension
fileExt = os.path.splitext(fileNames[0])[1]

cnt = 1
nums = fileNums + st - 1
if nums % 10 >= 9:
    cnt += 1
while True:
    div = nums // 10
    if div != 0:
        nums = div
        cnt += 1
    else:
        break

for (fileName, index) in zip(fileNames, range(st, fileNums + st)):
    if fileName.endswith(fileExt):
        origPath = os.path.join(path, fileName)
        newName = namePattern + '%0.{}d'.format(cnt) % index + fileExt
        newPath = os.path.join(path, newName)
        print('%s --> %s' % (fileName, newName))
        os.rename(origPath, newPath)

S.A.O. season-2 0100.mp4 --> S.A.O. season-2 15.mp4
S.A.O. season-2 0101.mp4 --> S.A.O. season-2 16.mp4
S.A.O. season-2 0102.mp4 --> S.A.O. season-2 17.mp4
S.A.O. season-2 0103.mp4 --> S.A.O. season-2 18.mp4
S.A.O. season-2 0104.mp4 --> S.A.O. season-2 19.mp4
S.A.O. season-2 0105.mp4 --> S.A.O. season-2 20.mp4
S.A.O. season-2 0106.mp4 --> S.A.O. season-2 21.mp4
S.A.O. season-2 0107.mp4 --> S.A.O. season-2 22.mp4
S.A.O. season-2 0108.mp4 --> S.A.O. season-2 23.mp4
S.A.O. season-2 0109.mp4 --> S.A.O. season-2 24.mp4

函数总结

  • os.path.split(): 返回最后一级目录或者文件
  • os.walk(): 返回一个目录树及文件的生成器
  • lis.sort(key=len): 对列表 lis 进行按照长度排序
  • os.path.splitext(): 从文件名中分离出文件扩展名
  • os.path.join(): 合并路径
  • os.rename(): 重命名文件

简单GUI

使用tkinter做的简单界面。
样图 (因为原文件带有广告,所以加了马赛克):

original

预览结果:

renamed1

重命名:

renamed2

评论

  1. root 博主
    4年前
    2019-3-05 19:40:30

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇