Ptrhon将windows默认换行符(\r\n)转换为unix默认换行符为(\n)

有时会发现在Linux下打开文件每行会多^M,这是因为windows默认换行符为\r\n,lunix默认换行符为\n。

image

解决方案

import os


def run(files, path=os.path.curdir):
    """
    将windows默认换行符(\r\n)转换为unix默认换行符为(\n)
    :param files:文件名称列表,可以进行批量转换
    :param path:文件的路径,如果和当前文件在同一文件夹下可以不传
    :return: None
    """
    for file in files:
        file_path = path + '\\' + file
        with open(file_path, "r") as f:
            result = f.read().replace(r'\r\n', r'\n')
        # 需要用二进制的方式('b')重写才会OK,否则会自动按照操作系统默认方式
        with open(file_path, "wb") as f:
            f.write(result.encode(encoding='utf-8'))


if __name__ == '__main__':
    files_list = ["a.sh"]
    run(files_list)

posted @ 2021-11-10 17:35  liuyang9643  阅读(391)  评论(0编辑  收藏  举报