Python 换行符转换
2015-12-25 11:26
796 查看
欢迎转载,转载请注明原文地址:/article/8326784.html
因为工作需求,需要把目录下的所有换行符转换为windows换行符'\r\n',文件太多,只好写一个简单的python脚本转换。
而且文件类型比较乱,既有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.
因为工作需求,需要把目录下的所有换行符转换为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.
相关文章推荐
- python 代码格式化工具:YAPF
- Python&按键精灵自动化
- python 爬一下
- Python学习之MySQLdb模块
- [转载]Pykd——Python extension for WinDbg
- Python官方
- 【python】sys.argv[] 的用法
- python基础----函数作为返回值
- [python]循环中的else子句
- 【python】dict的拷贝问题
- Python:Fatal error in launcher: Unable to create process using pip.exe
- 为python添加magic进行文件类型识别
- [转载]Python兵器谱
- python代码优化---就喜欢细节
- 排序算法—希尔排序算法分析与实现(Python)
- numpy转换
- Python教程
- 17个新手常见Python运行时错误
- Python异常
- Python标准库——走马观花