当前位置: 代码迷 >> 综合 >> python 批量转换文本文件的编码格式为utf-8 BOM
  详细解决方案

python 批量转换文本文件的编码格式为utf-8 BOM

热度:52   发布时间:2024-02-07 20:22:41.0

下列python可以将当前目录及子目录内的 .h和.c文件的编码批量转换为utf-8 BOM

 

```python

import chardet
import os

def get_encoding(file):
with open(file, "rb") as f:
data = f.read()
return chardet.detect(data)["encoding"]


for root, dirs, files in os.walk("."):
for name in files:
if os.path.splitext(name)[-1] in (".c",".h"):
file_name = os.path.join(root, name)
decoding = get_encoding(file_name)
print(file_name)
data = None
with open(file_name, "r", encoding = decoding) as f:
data = f.read()
with open(file_name, "w", encoding = "utf-8-sig") as f:
f.write(data)

```

  相关解决方案