Python实现把回车符\\r\\n转换成\\n
作者:junjie 时间:2022-09-21 07:22:14
最近在做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(二进制)模式打开。
标签:Python,回车符,\r\n,转换,\n
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python3的pip路径在哪
2023-01-27 14:15:39
Python自动化办公之手机号提取
2022-12-26 11:31:46
![](https://img.aspxhome.com/file/2023/4/133184_0s.gif)
python之pymysql模块简单应用示例代码
2024-01-22 00:22:45
激发你的灵感:50个优秀的Favicons设计
2007-10-21 19:52:00
![](https://img.aspxhome.com/file/UploadPic/200710/21/20071021211019426s.gif)
Python 操作 MongoDB 讲解详细
2021-11-28 10:00:46
![](https://img.aspxhome.com/file/2023/5/115735_0s.jpg)
Python查找文件中包含中文的行方法
2023-06-11 11:16:20
PHP的PDO错误与错误处理
2023-06-05 20:21:40
在Python的web框架中中编写日志列表的教程
2021-11-06 05:15:29
![](https://img.aspxhome.com/file/2023/0/102820_0s.png)
用Python爬取英雄联盟的皮肤详细示例
2023-05-07 22:41:19
![](https://img.aspxhome.com/file/2023/7/126997_0s.jpg)
Can't connect to MySQL server的解决办法
2024-01-19 07:30:31
Dreamweaver使用快技法十三则总结
2008-05-01 17:32:00
mysql 各种时间段查询
2010-01-06 13:37:00
如何理解Python中包的引入
2021-08-14 11:42:31
Pygame游戏开发之太空射击实战图像精灵下篇
2022-10-20 16:09:06
![](https://img.aspxhome.com/file/2023/5/65905_0s.png)
CMS不要让MySQL为你流泪
2008-12-11 14:38:00
python中正则表达式的使用详解
2023-08-08 14:47:13
![](https://img.aspxhome.com/file/2023/5/62285_0s.png)
Python使用20行代码实现微信聊天机器人
2023-12-04 12:52:06
![](https://img.aspxhome.com/file/2023/8/124638_0s.jpg)
使用Python实现图像标记点的坐标输出功能
2022-10-31 16:15:06
![](https://img.aspxhome.com/file/2023/9/68839_0s.jpg)
自学MySql内置函数知识点总结
2024-01-23 11:19:04
python3.3教程之模拟百度登陆代码分享
2023-08-02 23:08:23