时间:2021-07-01 10:21:17 帮助过:77人阅读
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(二进制)模式打开。