Python實現檔案編碼批量轉換

2021-10-12 03:17:09 字數 2099 閱讀 5353

突然翻出了之前寫的乙份**,適用於批量修改乙個目錄及其子目錄下所有指定型別的檔案編碼。使用了python的chardetcodecs庫。

# -*- coding: utf-8 -*-

import os, chardet, codecs, re

#檔案型別副檔名 檔案列表

filetype, filelist =

,[]def

get_file_list

(dir)

:""" 獲取指定目錄下所有指定型別檔案

"""if

len(dir.strip(

' '))==

0:return

dirlist =

[os.path.join(dir, f)

for f in os.listdir(dir)

] filelist =

[f for f in dirlist if os.path.isfile(f)

and os.path.splitext(f)[1

]in filetype]

folderlist =

[f for f in dirlist if os.path.isdir(f)

] filelist.extend(filelist)

# 遞迴字資料夾

for subfolder in folderlist:

get_file_list(subfolder)

defconvert_2_target_coding

(coding=

'utf-8'):

""" 轉換成目標編碼格式

"""for filepath in filelist:

with

open

(filepath,

'rb'

)as f:

data = f.read(

) codetype = chardet.detect(data)

['encoding'

]if codetype not

in(coding,

'ascii'):

with codecs.

open

(filepath,

'r', codetype)

as f:

content = f.read(

)with codecs.

open

(filepath,

'w', coding)

as f:

f.write(content)

print

(filepath +

'\n'

)if __name__ ==

'__main__'

:# 獲取目錄

workdir =

str(

input

('input target folder\n\t:'))

# 目標編碼格式

targetcoding =

str(

input

('target coding(default to utf-8)\n\t:'))

.lower(

)# 檔案型別副檔名

filetype = re.split(r'\s+'

,str

(input

('file type(filename extension, such as .c .h)\n\t:'))

) os.chdir(workdir)

get_file_list(workdir)

convert_2_target_coding(targetcoding)

使用方法:

直接啟動指令碼,按照提示,第一步輸入目標目錄的據對路徑(windows下直接拖拽到控制台);第二步輸入目標編碼格式,比如utf-8或者gb2312什麼的;第三步輸入目標型別副檔名,如果有多個就用空格隔開,例如.py .cpp .h如果要經常用的話建議拿pyinstaller打包一下,新增到環境變數裡面~

Python 批量修改檔案的編碼格式

使用說明 2 環境配置 python安裝 配置環境變數,chardet解壓放在python安裝目錄 lib site packages下 舉例 批量修改當前路徑下所有.cpp檔案的編碼格式為utf 8,如下 import os import sys import codecs import char...

python 批量檔案名字漢字轉拼音

coding utf8 import os import pypinyin from pypinyin import pinyin,lazy pinyin def rename path u c users er desktop hanzi2pinyin filelist os.listdir pa...

python實現批量檔案重新命名

問題描述 最近遇到朋友求助,如何將大量檔名前面的某些字元刪除。即將圖中檔案前的編號刪除。python實現 用到了python中的os模組,os模組中的rename方法可以實現對檔案的重新命名 import os path為批量檔案的資料夾的路徑 path d renamefolder 資料夾中所有檔...