下面小編就為大家帶來一篇Python 實作簡單的shell sed替換功能(實例講解)。小編覺得蠻不錯的,現在就分享給大家,也給大家做個參考。一起跟著小編過來看看吧
code:
f = open('yesterday','r',encoding='utf-8') f2 = open('yesterday.bak','w',encoding='utf-8') old_str = input('请输入要修改的字符:') replace_str = input('请输入替换成的字符:') for line in f.readlines(): line = line.replace(old_str,replace_str) print(line) f2.write(line) f.close() f2.close()
檔案內容:(yesterday)
Somehow, it seems the love I knew was always the most destructive kind 不知为何,我经历的爱情总是最具毁灭性的的那种 Yesterday when I was young 昨日当我年少轻狂 The taste of life was sweet 生命的滋味是甜的 As rain upon my tongue 就如舌尖上的雨露
感想:
思路很簡單就是開啟源文件,然後循環,把源文件要替換的內容替換再寫入新檔案!
以上是Python實作shell sed取代簡單的功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!