最近在做cocos2d-x的简明配置,发现有的朋友的文本编辑器,自动将\r\n截断成\n,(在unix上换行使用\n,windows上,换行使用的是\r\n)于是,写了这个脚本,希望对一些朋友有所帮助,不用一行一行去改
import osdef 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(二进制)模式打开。