批量修改文件编码.Python
时间: 2023-08-27 12:17:22 浏览: 73
你可以使用以下Python代码来批量修改文件编码:
```python
import os
from chardet import detect
def convert_encoding(path):
with open(path, 'rb') as fp:
content = fp.read()
encoding = detect(content)['encoding']
content = content.decode(encoding).encode('utf8')
with open(path, 'wb') as fp:
fp.write(content)
def batch_convert_encoding(directory):
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(('.c', '.cpp', '.h', '.hpp')):
path = os.path.join(root, file)
convert_encoding(path)
# 使用示例
batch_convert_encoding("目标文件夹目录")
```
这段代码会递归地遍历指定目录下的所有文件,并将后缀名为.c, .cpp, .h, .hpp的文件都转换为UTF-8编码。首先,它通过chardet库检测文件的原始编码。然后,将文件内容按照检测到的编码解码,并重新以UTF-8编码写入文件。这样就完成了批量修改文件编码的操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [python 批量修改文件编码](https://blog.csdn.net/Eternal_Whispers/article/details/120220132)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [python实现批量转换文件编码encoding](https://blog.csdn.net/awisc/article/details/120901910)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)