您的位置:首页 > 编程语言 > Python开发

Python 换行符转换

2015-12-25 11:26 796 查看
欢迎转载,转载请注明原文地址:/article/8326784.html

因为工作需求,需要把目录下的所有换行符转换为windows换行符'\r\n',文件太多,只好写一个简单的python脚本转换。

import os
import os.path
rootdir = r'D:/src'

def replace(filename):
try:
oldfile = open(rootdir+'/'+filename, 'rb+')
newfile = open(rootdir + '$' + filename, 'ab+')

old = b'\r'
new = b'\r\n'

data = b''
while (True):
data = oldfile.read(200)
newData = data.replace(old, new)
newfile.write(newData)
if len(data) < 200:
break
newfile.close()
oldfile.close()

os.remove(rootdir+'/'+filename)
os.rename(rootdir + '$' + filename, rootdir+'/'+filename)
except IOError as e:
print(e)

for parent,dirnames,filenames in os.walk(rootdir):
if parent[-3:] != 'src':  # 我只替换当前目录下的,不替换子目录
print "==:",parent
continue
for filename in filenames:
if filename[-4:] != '.cpp' and filename[-2:] != '.h':  # 只替换特定类型文件
print "file:",filename
continue
replace(filename)
#print "parent is:" + parent
#print "filename is:" + filename
#print "the full name of the file is:" + os.path.join(parent,filename)


而且文件类型比较乱,既有windows('\r\n'),linux('\n'),mac('r'),我要统一转为windows('\r\n')

就想到一种方法。

1.'\r\n'->'\r',

2.'\n'->'\r',

3.'\r'->'\r\n',

前两步先把\n去掉,全部换为\r,这样就方便全部替换为\r\n,不然总有多余的\r或者\n.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: