python文件格式(unix、windows)互换

您所在的位置:网站首页 mac与windows文件格式 python文件格式(unix、windows)互换

python文件格式(unix、windows)互换

2024-07-13 12:00| 来源: 网络整理| 查看: 265

    因为经常要把文件在windows和unix上通用,但是一些脚本文件因为unix和windows换行符的表示方式不同而导致文件存在各种各样的问题,所以特意写了一个把unix和windows文件相互转化的脚本程序。

    把windows文件转化成unix文件:

__author__ = 'L' import sys import os import stat def change_dos_to_unix(path): for item in os.listdir(path): subpath = os.path.join(path, item) mode = os.stat(subpath)[stat.ST_MODE] if stat.S_ISDIR(mode): continue else: with open(subpath, "rb+") as file_handle: all_text = file_handle.read() all_change_text = all_text.replace(b"\r\n", b"\n") print(len(all_change_text)) file_handle.seek(0, 0) file_handle.truncate() file_handle.write(all_change_text) print("change %s file to unix format." % subpath)

    这里在读取文件的时候一定要用二进制的模式去读取,因为只有二进制模式只读取到\r字符,如果是用文本模式去读取的话,是读取不到\r字符的。在替换字符的时候,把\r\n替换成\n就可以了,因为unix下面换行是\n,而windows是\r\n。

    unix文件替换成windows文件:

def change_unix_to_dos(path): for item in os.listdir(path): subpath = os.path.join(path, item) mode = os.stat(subpath)[stat.ST_MODE] if stat.S_ISDIR(mode): continue else: with open(subpath, "rb+") as file_handle: all_text = file_handle.read() all_change_text = all_text.replace(b"\n", b"\r\n") file_handle.seek(0, 0) file_handle.truncate() file_handle.write(all_change_text) print("change %s file to dos format." % subpath)

    这个刚好和上面相反。

    而在使用的时候,路径通过参数传进去,第2个参数用来标明转化方向。

if len(sys.argv) >= 2: current_path = sys.argv[1] if len(sys.argv) == 3: change_unix_to_dos(current_path) else: change_dos_to_unix(current_path)


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3