最近在做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(二進制)模式打開。
新聞熱點
疑難解答