使用 python 将 "\r\n" 转换为 "\n"
众所周知, Linux 下没有 "\r\n", 而 windows 下文本工具默认打开文件时使用 t 模式, 使得写入一行结尾的换行符为 "\r\n", 这样造成了一个极大的麻烦, 直接编辑的 sh 脚本程序无法在 Linux 中运行.
此工具可快速将解决此烦恼.
dosToUnix.py
""" 将 "\r\n" 转换为 "\n" """ import functools import argparse import os.path def main(): parser = argparse.ArgumentParser() parser.add_argument("-file", dest = "fileName") args = parser.parse_args() fileName = args.fileName assert fileName and os.path.exists(fileName), "file not found" with open(fileName, "rb") as f: data = bytearray(os.path.getsize(fileName)) f.readinto(data) # print(data) data = data.replace(b"\r\n", b"\n") with open(fileName, "wb") as f: # print(data) f.write(data) if __name__ == "__main__": main()
import sys import os def main(): filename = sys.argv[1] if len(sys.argv) > 1 else "" assert filename and os.path.exists(filename) with open(filename, "rb") as fp: data = fp.read() if not data: return data = data.replace(b"\r\n", b"\n") data = data.replace(b"\r\x00\n\x00", b"\n\x00") with open(filename, "wb") as fp: fp.write(data) if __name__ == '__main__': main()
代码养活自己