【python3】文件格式转换windows转为unix、utf-8


一、场景

       工作需要,有时要将文件上传到 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)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM