最近在做cocos2d-x的简明配置,发现有的朋友的文本编辑器,自动将\\r\\n截断成\\n,(在unix上换行使用\\n,windows上,换行使用的是\\r\\n)于是,写了这个脚本,希望对一些朋友有所帮助,不用一行一行去改
import os
def replace(filePath, w2u):
try:
oldfile = open(filePath, \"rb+\") #这里必须用b打开
path, name = os.path.split(filePath)
newfile = open(path + \'$\' + name, \"ba+\")
old = b\'\'
new = b\'\'
if w2u == True:
old = b\'\\r\'
new = b\'\'
else:
old = b\'\\n\'
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(filePath)
os.rename(path + \'$\' + name, filePath)
except IOError as e:
print(e)
if __name__ == \"__main__\":
print(\"请输入文件路径:\")
filePath = input()
replace(filePath, False) #这个改为True就可以实现\\n变成\\r\\n
要注意的是,在python里,像\\r\\n这样的符号,如果是文本打开的话,是找不到\\r\\n的,而只能找到\’\\n\’,所以必须用b(二进制)模式打开。