Python3 实现文件批量重命名示例代码
作者:Linux 时间:2023-06-18 00:08:32
在Python中os模块里,os.renames()
方法用于递归重命名目录或文件。类似rename()。
rename()方法语法格式如下:
os.rename(old,new)
old是需要修改的目录/文件名,new是修改后的目录/文件名,通过这个方法我们可以很轻松的完成批量在文件/目录增加固定前缀或者批量删除文件/目录固定前缀 。
以下代码Windows下和Linux都可以使用。
示例如下:
增加前缀'[Linuxidc.]':
import os
path='/home/linuxidc/linuxidc.com'
old_dir=os.listdir(path) #获取/home/linuxidc/linuxidc.com目录下的所有文件目录
print("原始目录为 %s"%old_dir)
for i in old_dir:
new_name='[Linuxidc.]'+i
os.rename(i,new_name)
new_dir=os.listdir(path)
print("现在的目录为%s"%new_dir)
运行后输出如下:
删除前缀'[Linuxidc.]':
import os
path='/home/linuxidc/linuxidc.com'
old_dir=os.listdir(path)
print("原始目录为 %s"%old_dir)
for i in old_dir:
shu=i.rfind(']') #获取到']'的位置
new_name=i[shu+1:]
os.rename(i,new_name)
new_dir=os.listdir(path)
print("现在的目录为%s"%new_dir)
运行后输出如下:
原始目录为 ['[Linuxidc.]linuxidc.com.sh', '[Linuxidc.]kakoune', '[Linuxidc.]linuxidc', '[Linuxidc.]linuxidc.Java', '[Linuxidc.]linuxidc.com.jpg', '[Linuxidc.]opencv-3.4.0', '[Linuxidc.]linuxidc.class', '[Linuxidc.]Linux公社www.linuxidc.com.py', '[Linuxidc.]linuxidc.com.txt', '[Linuxidc.]linuxidc.txt', '[Linuxidc.]linuxidcbuild', '[Linuxidc.]amp', 'www.linuxidc.com.py', '[Linuxidc.]linuxidc.sh', '[Linuxidc.]linuxisdc.com.jpg', '[Linuxidc.]www.linuxidc.com', '[Linuxidc.]linuxidc.com.png', '[Linuxidc.].vimrc', '[Linuxidc.]tupian']
现在的目录为['linuxidc.txt', 'www.linuxidc.com', 'linuxidc.java', 'linuxidc.com.png', 'amp', 'Linux公社www.linuxidc.com.py', 'linuxidc.class', 'linuxisdc.com.jpg', 'linuxidc', 'opencv-3.4.0', 'www.linuxidc.com.py', 'linuxidc.com.sh', '.vimrc', 'linuxidcbuild', 'kakoune', 'tupian', 'linuxidc.sh', 'linuxidc.com.txt', 'linuxidc.com.jpg']
[Finished in 0.1s]
在Windows下还需要注意一下文件路径应使用双斜杠// ,否则会出现错误,Linux下一般不会出现此错误。
总结
以上所述是小编给大家介绍的Python3 实现文件批量重命名示例代码,网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
来源:https://www.linuxidc.com/Linux/2019-06/158935.htm
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python简单删除列表中相同元素的方法示例
python对站点数据做EOF且做插值绘制填色图
![](https://img.aspxhome.com/file/2023/8/93488_0s.png)
python自动化运维之Telnetlib的具体使用
TensorFlow人工智能学习数据合并分割统计示例详解
![](https://img.aspxhome.com/file/2023/5/67275_0s.png)
安装pytorch时报sslerror错误的解决方案
![](https://img.aspxhome.com/file/2023/7/95387_0s.jpg)
Python内存泄漏和内存溢出的解决方案
WAP中的ASP技术
理解Javascript的caller,callee,call,apply区别
100%点击区的滑动门
Android分包MultiDex策略详解
python学习之新式类和旧式类讲解
![](https://img.aspxhome.com/file/2023/1/108141_0s.png)
Django中auth模块用户认证的使用
SQL Server2016正式版安装配置方法图文教程
![](https://img.aspxhome.com/file/2023/6/110976_0s.jpg)
浅谈python中的__init__、__new__和__call__方法
Python 实现Numpy中找出array中最大值所对应的行和列
![](https://img.aspxhome.com/file/2023/7/103787_0s.jpg)
:hover在IE6下的问题
Python读取txt某几列绘图的方法
javascript过滤数组重复元素的实现方法
JavaScript 组件之旅(三):用 Ant 构建组件
Pandas数据集的分块读取的实现
![](https://img.aspxhome.com/file/2023/3/117973_0s.jpg)