在文本编辑器中会自动将\r\n截断成\n,(在unix上换行使用\n,windows上,换行使用的是\r\n)于是,写了这个脚本,不用一行一行去改。来具体看下如何实现的:
![图片[1]-Python怎么把/r/n替换成/n?-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5d1190a953f87955.jpg)
importos
defreplace(filePath,w2u):
try:
oldfile=open(filePath,"rb+")#这里必须用b打开
path,name=os.path.split(filePath)
newfile=open(path+'$'+name,"ba+")
old=b''
new=b''
ifw2u==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)
iflen(data)<200:
break
newfile.close()
oldfile.close()
os.remove(filePath)
os.rename(path+'$'+name,filePath)
exceptIOErrorase:
print(e)
if__name__=="__main__":
print("请输入文件路径:")
filePath=input()
replace(filePath,False)#这个改为True就可以实现\n变成\r\n原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END


















































暂无评论内容