一、場景
工作需要,有時要將文件上傳到 linux 的服務器,希望將文件的格式改為 Unix(LF) 、 utf-8, 可以通過py腳本來批量處理。
二、代碼
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2019/12/2 11:22 # @Author : way # @Site : # @Describe: 檢查 腳本文件 轉換格式為 LF , utf-8 import sys import os import chardet def turn(file): with open(file, 'rb') as f: data = f.read() encoding = chardet.detect(data)['encoding'] data_str = data.decode(encoding) tp = 'LF' if '\r\n' in data_str: tp = 'CRLF' data_str = data_str.replace('\r\n', '\n') if encoding not in ['utf-8', 'ascii'] or tp == 'CRLF': with open(file, 'w', newline='\n', encoding='utf-8') as f: f.write(data_str) print(f"{file}: ({tp},{encoding}) trun to (LF,utf-8) success!") if __name__ == "__main__": if sys.argv.__len__() != 2: print(f"param: python3 etl_file_check.py /home/getway/script/hql") else: dr = sys.argv[1] for path in os.listdir(dr): file = os.path.join(dr, path) if os.path.isfile(file): turn(file)