我们经常会遇到比如下载了一堆壁纸或者MP3之类的,想要给这些文件名添加一个序号。
于是我根据 Python 使用 os 模块显示目录下的文件,以及使用 os 模块给文件重命名的知识点,写了下面一个程序。实现同类型的文件按照顺序,在原文件名后面增加指定位数的序号,并把后缀名改为小写。里面还
比如 壁纸.JPG 重命名为 壁纸-001.jpg
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import os file_type = input ( '输入文件后缀名,直接回车修改所有文件\n请输入想要处理的文件类型(jpg/png/mp3/...):' ) if file_type: if not file_type.count( '.' ): file_type = '.' + file_type print ( '\n您想修改的文件后缀是' ,file_type, '\n' ) else : print ( '\n您要修改的是所有文件。\n' ) bits = input ( '序号位数(直接输入数字,默认为3):' ) if bits.isdigit(): bits = int (bits) else : bits = 3 def check_type(file_type): # 检查是否输入后缀的自定义函数 if file_type: check = file .lower().endswith(file_type) else : check = True return check print ( '========Start=======' ) f_type = '' for file in os.listdir(): if check_type(file_type) and not file .endswith( '.py' ) and not os.path.isdir( file ): f_name,f_ext = os.path.splitext( file ) # 把文件名分割成名称和后缀 f_ext = f_ext.lower() # 把后缀全部转为小写 if not f_type = = f_ext: # 后缀变了之后,重新编码 i = 0 print (f '\n*** {f_ext} ***\n' ) i + = 1 f_num = format (i,f '0{bits}d' ) # 按照位数格式化数字 f_new = f '{f_name}-{f_num}{f_ext}' # 添加序号之后的新文件名 f_type = f_ext os.rename( file ,f_new) print ( file , '>' ,f_new) print ( '========End=======' ) |
里面还用到了数字格式化的方法,比如想要把数字 1 变成 001 这种格式可以用下面这种方法:
1 | format ( 1 , '03d' ) |
关键是后面的参数 03d,0代表位数不足补0,3代表3位数,d代表数字。
格式化也是非常有意思的一种方法,之后有机会专门展开讲解一下。
更多Python学习日志,点击:Python学习日志目录
下一篇:案例:用 Python 把最近三个月未修改过的文件进行压缩备份
上一篇:Python 函数与函数的自定义
- 相关文章 -
Python 基础知识入门演示 - 2017-12-31
Python 数字与数字型运算 - 2020-09-08
Python 基础知识之数据类型 - 2020-09-07
Python 学习中非常好用的编辑器 Sublime Text 3 - 2020-09-07
Python 基础知识之变量 - 2020-09-03
Python 详细安装步骤图解 - 2020-09-01
Python 数据分析模块 Pandas 之 DataFrame 数据 - 2020-02-09
Python 数据分析模块 Pandas 之 Series 数据 - 2020-02-05
- 文章评论 -
- 最新评论[0条评论] -
版权所有©逍遥峡谷 - 星际中心超自然局 · 地球总部 |
逍遥峡谷 ·
酷品优选
Copyright©Interstellar Central Occult Agency (I.C.O.A)
本局纯属虚构,如有雷同,纯属巧合