python 修改文件后缀名
时间: 2024-01-25 11:13:00 浏览: 30
以下是两种Python修改文件后缀名的方法:
1. 使用os模块的rename()函数
```python
import os
def change_suffix(path, old_suffix, new_suffix):
for file in os.listdir(path):
if file.endswith(old_suffix):
old_name = os.path.join(path, file)
new_name = os.path.join(path, file.replace(old_suffix, new_suffix))
os.rename(old_name, new_name)
# 示例用法
change_suffix('/path/to/folder', '.txt', '.csv')
```
2. 使用pathlib模块的rename()方法
```python
from pathlib import Path
def change_suffix(path, old_suffix, new_suffix):
folder = Path(path)
for file in folder.iterdir():
if file.suffix == old_suffix:
new_name = file.with_suffix(new_suffix)
file.rename(new_name)
# 示例用法
change_suffix('/path/to/folder', '.txt', '.csv')
```