zoukankan      html  css  js  c++  java
  • 【python3】文件格式转换windows转为unix

    一、场景

           工作需要,有时要将文件上传到 unix 的服务器,希望将文件的格式改为 Unix(LF), 可以通过py脚本来批量处理。

    二、代码

    复制代码
    import os
    
    # 转换文件格式和编码方式
    def to_lf(path, isLF, encoding = 'utf-8'):
        """
        :param path: 文件路径
        :param isLF: True 转为Unix(LF)  False 转为Windows(CRLF)
        :param encoding: 编码方式,默认utf-8
        :return:
        """
        newline = '
    ' if isLF else '
    '
        tp = 'Unix(LF)' if isLF else 'Windows(CRLF)'
        with open(path, newline=None, encoding=encoding) as infile:
            str = infile.readlines()
            with open(path, 'w', newline=newline, encoding=encoding) as outfile:
                outfile.writelines(str)
                print("文件转换成功,格式:{0} ;编码:{1} ;路径:{2}".format(tp, encoding, path))
    
    if __name__ == "__main__":
        rootdir = r'C:UsersAdministratorDesktop	estl'
        isLF = True  # True 转为Unix(LF)  False 转为Windows(CRLF)
        path_list = os.listdir(rootdir)
        #path_list.sort(key=lambda x:int(x[:-4])) #对读取的路径进行排序
        for filename in path_list:
            path = os.path.join(rootdir,filename)
            to_lf(path, isLF)
    复制代码
  • 相关阅读:
    学习进度条
    阅读《实例化需求》10-12章有感
    学习进度条
    阅读《实例化需求》7–9章有感
    学习进度条
    软件需求与分析课堂讨论一
    课程引言课后作业1
    MVC实例应用模式
    MVC模式介绍
    二十三种设计模式
  • 原文地址:https://www.cnblogs.com/haitaoli/p/10986004.html
Copyright © 2011-2022 走看看