zoukankan      html  css  js  c++  java
  • 【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 '
    ' in data_str:
                tp = 'CRLF'
                data_str = data_str.replace('
    ', '
    ')
            if encoding not in ['utf-8', 'ascii'] or tp == 'CRLF':
                with open(file, 'w', newline='
    ', 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)
  • 相关阅读:
    linux-shell编程-1-简介
    linux-tail
    linux-grep
    linux-sort
    linux-sed
    linux-awk
    函数调用
    选择结构和循环结构
    列表字典集合常用函数
    datetime模块
  • 原文地址:https://www.cnblogs.com/TurboWay/p/9687576.html
Copyright © 2011-2022 走看看