Python3 文件基本修改替换
生活随笔
收集整理的這篇文章主要介紹了
Python3 文件基本修改替换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
現有原文件:
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知為何,我經歷的愛情總是最具毀滅性的的那種 3 Yesterday when I was young 4 昨日當我年少輕狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game 10 我戲弄生命 視其為愚蠢的游戲 11 The way the evening breeze 12 就如夜晚的微風 13 May tease the candle flame 14 逗弄蠟燭的火苗 15 The thousand dreams I dreamed 16 我曾千萬次夢見 17 The splendid things I planned 18 那些我計劃的絢麗藍圖 19 I always built to last on weak and shifting sand 20 但我總是將之建筑在易逝的流沙上 21 I lived by night and shunned the naked light of day 22 我夜夜笙歌 逃避白晝赤裸的陽光 23 And only now I see how the time ran away 24 事到如今我才看清歲月是如何匆匆流逝 25 Yesterday when I was young 26 昨日當我年少輕狂 27 So many lovely songs were waiting to be sung 28 有那么多甜美的曲兒等我歌唱 29 So many wild pleasures lay in store for me 30 有那么多肆意的快樂等我享受 31 And so much pain my eyes refused to see 32 還有那么多痛苦 我的雙眼卻視而不見 33 I ran so fast that time and youth at last ran out 34 我飛快地奔走 最終時光與青春消逝殆盡 35 I never stopped to think what life was all about 36 我從未停下腳步去思考生命的意義 37 And every conversation that I can now recall 38 如今回想起的所有對話 39 Concerned itself with me and nothing else at all 40 除了和我相關的 什么都記不得了 41 The game of love I played with arrogance and pride 42 我用自負和傲慢玩著愛情的游戲 43 And every flame I lit too quickly, quickly died 44 所有我點燃的火焰都熄滅得太快 45 The friends I made all somehow seemed to slip away 46 所有我交的朋友似乎都不知不覺地離開了 47 And only now I'm left alone to end the play, yeah 48 只剩我一個人在臺上來結束這場鬧劇 49 Oh, yesterday when I was young 50 噢 昨日當我年少輕狂 51 So many, many songs were waiting to be sung 52 有那么那么多甜美的曲兒等我歌唱 53 So many wild pleasures lay in store for me 54 有那么多肆意的快樂等我享受 55 And so much pain my eyes refused to see 56 還有那么多痛苦 我的雙眼卻視而不見 57 There are so many songs in me that won't be sung 58 我有太多歌曲永遠不會被唱起 59 I feel the bitter taste of tears upon my tongue 60 我嘗到了舌尖淚水的苦澀滋味 61 The time has come for me to pay for yesterday 62 終于到了付出代價的時間 為了昨日 63 When I was young 64 當我年少輕狂 View Code如果我們要修改其中一些文字,可以運用以下:
1 y = open('yesterday','r') 2 y_new = open('yesterday_new','w') 3 tihuan = input('輸入要替換的替換:') 4 tihuan_new = input('輸入要替換的替換:') 5 6 for i in y: 7 if tihuan in i: 8 i = i.replace(tihuan,tihuan_new) 9 y_new.write(i)找出yesterday文件,如果要修改什么,可以input輸入:,比如要修改其中的
1 So many wild pleasures lay in store for me 2 有那么多肆意的快樂等我享受把我修改成Tuskasa:
可以
tihuan = input('輸入要替換的替換:') 輸入:有那么多肆意的快樂等我享受再輸入:有那么多肆意的快樂等Tuskasa享受
就會創建一個新的文件并修改(注意是創建一個新的文件,這樣我們就可以保存原文件,避免丟失)
或者可以另外定義: 1 import sys 2 find_str = sys.argv[1] 3 replace_str = sys.argv[2] 4 5 y = open('yesterday','r') 6 y_new = open('yesterday_new','w') 7 8 for i in y: 9 if find_str in i: 10 i = i.replace(find_str,replace_str) 11 y_new.write(i)
?
注意一定要記得close()文件
轉載于:https://www.cnblogs.com/Tsukasa/p/6575970.html
總結
以上是生活随笔為你收集整理的Python3 文件基本修改替换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 脚本录制软件python 按键精灵 tc
- 下一篇: 使用多种格式转换方法将MKV转成GIF