使用Python批量對文本文件編碼互轉(zhuǎn)的方法
在Windows下寫C語言默認是GB2312,放到Linux上就會亂碼,因為Linux和MacOS默認是UTF-8,因此寫了個Python小腳本對指定路徑下的文件進行轉(zhuǎn)換。
from sys import argv
import os
from chardet import detect
from codecs import lookup
CONFIG_FILE = '.any2any'
DEFAULT_CONFIG = '''
.c
.h
.cpp
.hpp
.hxx
.cc
.cxx
.C
.c++
.m
.cs
.rs
.java
.kt
.php
.pm
.pl
.py
.sh
.go
.xml
.htm
.html
.css
.js
.jsx
.vue
.txt
.csv
'''
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r') as config_file:
file_extension = tuple(config_file.read().split())
else:
file_extension = tuple(DEFAULT_CONFIG.split())
print(f"將轉(zhuǎn)換 {' '.join(list(file_extension))}")
def bytes_encoding(b: bytes, length: int = 1024) -> str:
'''
返回探測到的編碼格式
'''
return detect(b[:length])['encoding']
def any2any(b: bytes, encoding: str) -> bytes:
'''
任意編碼字節(jié)轉(zhuǎn)換為任意編碼字節(jié)
探測輸入的字節(jié)編碼格式,轉(zhuǎn)換為指定編碼,并返回對應(yīng)字節(jié)
'''
file_encoding = bytes_encoding(b)
if file_encoding == encoding:
return b
return lookup(encoding).encode(lookup(file_encoding).decode(b)[0])[0]
def allfileset(path: str = '.', filepathset: set = set()) -> set:
'''
遞歸路徑下所有文件,返回絕對路徑集合
'''
if os.path.isdir(path):
for item in os.listdir(path):
filepath = os.path.join(path, item)
if os.path.isfile(filepath):
filepathset.add(os.path.abspath(filepath))
else:
allfileset(filepath, filepathset)
else:
filepathset.add(os.path.abspath(path))
return filepathset
def is_valid_inputs() -> bool:
'''
檢查參數(shù)是否輸入正確
'''
return len(argv) > 1 and all(map(os.path.exists, argv[1:]))
def is_valid_encoding(encoding: str) -> bool:
'''
檢查是否存在指定編碼
'''
try:
lookup(encoding)
return True
except:
return False
def choice_encoding() -> str:
choice = input('''!??!在轉(zhuǎn)換前注意備份文件!??!
要轉(zhuǎn)換到什么編碼?
1. GB18030(Windows下常用,C語言不會亂碼)
2. UTF-8(非Windows下通用,例如Linux和macOS)
3. 其他
> ''')
if choice == '1':
return 'GB18030'
elif choice == '2':
return 'UTF-8'
elif choice == '3':
choice = input('輸入你想轉(zhuǎn)換到的編碼:')
while not is_valid_encoding(choice):
choice = input('不存在該編碼,重新輸入:')
return choice
else:
print('不做任何操作')
exit()
def main():
if is_valid_inputs():
encoding = choice_encoding()
filepathset = set()
for path in argv[1:]:
filepathset.union(filter(lambda s: s.endswith(file_extension), allfileset(path, filepathset)))
if filepathset:
for path in filepathset:
with open(path, 'rb') as f:
filebytes = any2any(f.read(), encoding)
with open(path, 'wb') as f:
f.write(filebytes)
print(f'{path} 已轉(zhuǎn)換到 {encoding}')
print('轉(zhuǎn)換已完成')
else:
print('沒有任何可以轉(zhuǎn)換的文件,請檢查程序下是否有.any2any配置文件,用空格或換行間隔要轉(zhuǎn)換的文件類型,例如 .c .cpp .cs')
else:
print("未收到任何要轉(zhuǎn)換的文件或文件夾路徑,或參數(shù)錯誤,請把要轉(zhuǎn)換的文件或文件夾拖動到程序上。")
if __name__ == "__main__":
try:
main()
finally:
input('按任意鍵退出...')可以使用pyinstaller打包成可執(zhí)行文件,帶著走或者分享給其他人用
安裝pyinstaller
conda install pyinstaller
打包Python文件,其中-i參數(shù)可以給.exe文件加上圖標,-F參數(shù)指定要打包的腳本
pyinstaller -i icon.ico -F any2any.py
最后打包好的可執(zhí)行文件在dict路徑下
到此這篇關(guān)于使用Python批量對文本文件編碼互轉(zhuǎn)的方法的文章就介紹到這了,更多相關(guān)Python批量轉(zhuǎn)換文本文件編碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
安裝pyhttpx解決ImportError: DLL load failed錯誤
這篇文章主要為大家介紹了安裝pyhttpx解決ImportError: DLL load failed錯誤,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
Python實現(xiàn)多子圖繪制系統(tǒng)的示例詳解
這篇文章主要介紹了如何利用python實現(xiàn)多子圖繪制系統(tǒng),文中的示例代碼講解詳細,具有一定的的參考價值,感興趣的小伙伴可以跟隨小編一起學習一下2023-09-09
OpenCV 使用imread()函數(shù)讀取圖片的六種正確姿勢
這篇文章主要介紹了OpenCV 使用imread()函數(shù)讀取圖片的六種正確姿勢,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07
python實現(xiàn)網(wǎng)站用戶名密碼自動登錄功能
最近接到這樣的需求通過網(wǎng)頁用戶認證登錄實現(xiàn)上網(wǎng),如何實現(xiàn)網(wǎng)站自動登錄功能呢,接下來小編給大家?guī)砹藀ython實現(xiàn)網(wǎng)站用戶名密碼自動登錄功能,需要的朋友可以參考下2019-08-08
使用Django實現(xiàn)把兩個模型類的數(shù)據(jù)聚合在一起
這篇文章主要介紹了使用Django實現(xiàn)把兩個模型類的數(shù)據(jù)聚合在一起,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
Python數(shù)值方法及數(shù)據(jù)可視化
這篇文章主要介紹了Python數(shù)值方法及數(shù)據(jù)可視化,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09

