批量替换多个文件夹下的图片
时间: 2023-08-07 14:02:59 浏览: 232
可以使用Python的os模块和shutil模块来批量替换多个文件夹下的图片。
具体步骤如下:
1. 导入os模块和shutil模块
```python
import os
import shutil
```
2. 遍历指定目录下的所有文件夹
```python
root_path = './images' # 指定根目录
for root, dirs, files in os.walk(root_path):
for filename in files:
filepath = os.path.join(root, filename) # 获取文件路径
# 对文件进行操作
```
3. 对图片文件进行操作
根据文件扩展名来判断是否为图片文件,然后使用字符串替换函数replace()替换文件名称中的特定字符。例如,将所有文件名称中的字符"old"替换成"new"。
```python
if filename.endswith('.jpg') or filename.endswith('.png'): # 判断是否为图片文件
new_filename = filename.replace('old', 'new') # 替换字符
new_filepath = os.path.join(root, new_filename) # 新文件路径
os.rename(filepath, new_filepath) # 修改文件名称
```
完整代码示例:
```python
import os
import shutil
root_path = './images' # 指定根目录
for root, dirs, files in os.walk(root_path):
for filename in files:
filepath = os.path.join(root, filename) # 获取文件路径
if filename.endswith('.jpg') or filename.endswith('.png'): # 判断是否为图片文件
new_filename = filename.replace('old', 'new') # 替换字符
new_filepath = os.path.join(root, new_filename) # 新文件路径
os.rename(filepath, new_filepath) # 修改文件名称
```
这样就可以批量替换多个文件夹下的图片了。
阅读全文
相关推荐
![exe](https://img-home.csdnimg.cn/images/20241231044909.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)