本文已参与「新人创作礼」活动,一起开启掘金创作之路。
前言
在上一篇中学习到了 python 的 os 和 re 模块,回顾一下
- os模块提供了非常丰富的方法用来处理文件和目录
- 通过内嵌集成re模块,程序可以直接调用来实现正则匹配
4、os模块中的listdir 和 rename
os.listdir()方法用于返回指定的文件夹包含的文件或文件夹的名字的列表
os.rename()方法用于重命名文件或目录。
os.rename(oldpath,newpath)
- -oldpath 要修改的目录名或文件名
- -newpath 修改后的目录名或文件名
import os
# 获取到文件夹下的所有文件名字
result = os.listdir('C:/Users')
# print(result)
oldpath = os.path.join('C:/Users','phone-v.png')
newpath = os.path.join('C:/Users','phone.png')
print(oldpath)
# 修改名字的方法
os.rename(oldpath,newpath)
结果:
C:/Users/phone-v.png
5、自动化修改文件名
在了解以上知识,我们就能够动手开始自动化修改文件名了,功能包括,在头部添加、在尾部添加、替换、指定类型文件
- target_dir 文件路径
- addstr 添加/修改的字段
- position
- end 在尾部添加
- head 在头部添加
- replace 替换
- oldstr 需要替换的文本
- newstr 替换后的新文本
# 批量修改文件名字
import re
def filename_modify(target_dir,addstr='',position = 'end',oldstr='',newstr='',filetype=''):
# 1. 判断路径是否存在
if os.path.exists(target_dir)==False:
raise Exception('路径下不存在该文件')
# 2. 遍历文件夹中的文件名
for file in os.listdir(target_dir):
# 分割文件名和扩展名 ('文件名','')
filename = os.path.splitext(file)[0]
fileExpand = os.path.splitext(file)[1]
# 不修改文件夹的名字
if fileExpand == '':
continue
# 过滤文件的类型,从而达到修改指定类型
if filetype != None and filetype not in fileExpand:
continue
# 判断添加的位置
if(position == 'end'):
# 将所有文件的后面添加 -new
newname = filename + addstr + fileExpand
elif position == 'head':
newname = addstr + filename + fileExpand
elif position == 'replace':
pattern = re.findall(oldstr,filename)
for value in pattern:
filename = filename.replace(value,newstr)
newname = filename + fileExpand
# 修改名字
oldpath = os.path.join(target_dir,file)
newpath = os.path.join(target_dir,newname)
os.rename(oldpath,newpath)
# print(newname)
pass
filename_modify('C:/Users/Untitled Folder/new文件夹',position='head',addstr='ABC-',filetype='xlsx')