python在文本編輯器中會自動將\r\n截斷成\n,(在unix上換行使用\n,windows上,換行使用的是\r\n)于是,寫了這個腳本,不用一行一行去改。來具體看下如何實現(xiàn)的:
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就可以實現(xiàn)\n變成\r\n
要注意的是,在python里,像\r\n這樣的符號,如果是文本打開的話,是找不到\r\n的,而只能找到'\n',所以必須用b(二進制)模式打開。
以上內(nèi)容為大家介紹了Python培訓之怎么把/r/n替換成/n?,希望對大家有所幫助,如果想要了解更多Python相關(guān)知識,請關(guān)注IT培訓機構(gòu):千鋒教育。