[Github Star多的py代码鉴赏学习]目录下文件重命名脚本
2018-02-10 15:30
211 查看
来源
batch_file_rename.py解析
1.程序入口if __name__ == '__main__': main()
2.使用模块
import os import argparse
OS模块 是一个Python的系统编程的操作模块,可以处理文件和目录等日常操作,可以输入help(os)查看详细的说明和使用介绍。
argparse模块 能对命令行参数进行解析,在使用这个脚本时需要带参数,这个模块就是解析从终端传进来的参数。其用法资料很多,之后碰到再补充。
2.Main方法内容
def main(): ''' This will be called if the script is directly invoked. ''' # adding command line argument parser = get_parser() args = vars(parser.parse_args()) # Set the variable work_dir with the first argument passed work_dir = args['work_dir'][0] # Set the variable old_ext with the second argument passed old_ext = args['old_ext'][0] if old_ext[0] != '.': old_ext = '.' + old_ext # Set the variable new_ext with the third argument passed new_ext = args['new_ext'][0] if new_ext[0] != '.': new_ext = '.' + new_ext batch_rename(work_dir, old_ext, new_ext)
可以看到内容很少
parser = get_parser() 调用了一个自定义的方法,get_parser的返回值是一个解析处理器,就是之前说的argparse模块里的东西
看看这个自定义方法
def get_parser(): parser = argparse.ArgumentParser(description='change extension of files in a working directory') parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1, help='the directory where to change extension') parser.add_argument('old_ext', metavar='OLD_EXT', type=str, nargs=1, help='old extension') parser.add_argument('new_ext', metavar='NEW_EXT', type=str, nargs=1, help='new extension') return parser
第一行生成了一个解析处理器,带有描述
第二、三、四行将参数添加进处理器里面,参数依次是,Key,命令行参数,参数类型,命令行应该消耗的参数数量,帮助上的说明
实际调用的时候注意 python 1.py /home/yg/code/python/test/1/imgs .jpeg .jpg 参数按顺序写,不要写WORK_DIR=/home/yg/code/python/test/1/imgs 这样的。不知道具体什么原因,argparse没用过,有知道的大神在评论里解释下,万分感谢。
args = vars(parser.parse_args())这句将获取的参数值存成字典调用
work_dir = args['work_dir'][0]获取路径参数,从上面可以知道,所有的参数值都是str型
获取现扩展名,如果输入的扩展名没有带.字符 就加上去 ,新扩展名同理
old_ext = args['old_ext'][0] if old_ext[0] != '.': old_ext = '.' + old_ext
最后调用修改方法
batch_rename(work_dir, old_ext, new_ext)
def batch_rename(work_dir, old_ext, new_ext): ''' This will batch rename a group of files in a given directory, once you pass the current and new extensions ''' # files = os.listdir(work_dir) for filename in os.listdir(work_dir): # Get the file extension split_file = os.path.splitext(filename) file_ext = split_file[1] # Start of the logic to check the file extensions, if old_ext = file_ext if old_ext == file_ext: # Returns changed name of the file with new extention newfile = split_file[0] + new_ext # Write the files os.rename( os.path.join(work_dir, filename), os.path.join(work_dir, newfile) )
思路很简单,首先拿到第一个行参传进来的文件目录下的所有文件名
使用os.path.splitext(filename)将名字拆成文件名和扩展名存在split_file里
split_file[0]是文件名 split_file[1]是扩展名(带点的)
循环比较文件的扩展名是否是需要被替换的
如果是那文件名与新扩展名加在一起生成新文件
然后执行os.rename()把work_dir\filename,替换成work_dir\newfile。
拓展
写了个类似的,批量重命名脚本,主要是因为是为相机里导出的图片命名,采用可与上面不同的命令行参数处理方法,getopt模块,比较好读懂些,可以-h -i这样调用,比较习惯这种的。用的都是常见模块,所以不做解析了,楼主自学,有写错或是说错的 还请各位留言告知,先谢谢啦。import os
import getopt, sys
def rename(work_dir, new_name, start_index):
for filename in os.listdir(work_dir):
split_file = os.path.splitext(filename)
4000
file_ext = split_file[1]
newfile = new_name+str(start_index)+file_ext
os.rename(
os.path.join(work_dir, filename),
os.path.join(work_dir, newfile)
)
start_index = start_index+1
def main():
opts, args = getopt.getopt(sys.argv[1:], "hd:i:n:", ["help=", "work_dir=", "start_index=", "new_name="])
work_dir = ""
new_name = "default"
start_index = 0
def usage():
print("""
-h --help print the help
-d --work_dir work_dir
-n --new_name new_name
-i --start_index start_index
""")
for op, value in opts:
if op in ("-d","--work_dir"):
work_dir = value
elif op in ("-i","--start_index"):
start_index = int(value)
elif op in ("-n","--new_name"):
new_name = value
elif op in ("-h"):
usage()
sys.exit()
rename(work_dir, new_name, start_index)
if __name__ == '__main__': main()
相关文章推荐
- 批量转换目录下文件编码的shell脚本代码
- 基于Python SimpleHTTPServer.py的修改脚本:HTTP文件服务器,修正中文目录列表,支持视频文件在线播放
- 小脚本,统计一个目录下满足特定条件文件的代码行数
- linux运用shell脚本统计列出目录文件个数(学习笔记)
- C++ 删除、重命名文件 、获取当前目录所有文件代码
- java代码实现根据JSON文件进行批量文件重命名或者改目录结构
- python写一段脚本代码自动完成输入(目录下的所有)文件的数据替换(修改数据和替换数据都是输入的)
- 查找目录下同名但不同后缀名文件的shell脚本代码
- 代码的文件和路径命名规范和目录结构规划
- golang代码文件目录组织、包目录组织学习笔记
- py中的目录与文件判别代码
- 在指定目录查找指定后缀文件的shell脚本代码
- python---把tab.py的tab键自动补齐命令脚本,放入包目录下,python所有文件都可以使用
- python 学习记录(11)-文件处理/读取文件/文件写入内容/文件删除/文件复制/文件重命名/后缀名/内容查找与替换/文件比较/ 配置文件访问/目录创建与删除/遍历目录/定向输出
- 批量转换目录下文件编码的shell脚本代码
- 在指定目录查找指定后缀文件的shell脚本代码
- 查找目录下同名但不同后缀名文件的shell脚本代码
- python写一段脚本代码自动完成输入(目录下的所有)文件的数据替换(修改数据和替换数据都是输入的)【转】
- Python和perl实现批量对目录下电子书文件重命名的代码分享
- 利用小马下载全站程序,(php inc格式文件包括目录结构)的py代码