windows上的python能否在unix上使用_python文件格式(unix、windows)互换

因为经常要把文件在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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值