Python實踐之路4——實現進度條和文件內容參數替換
阿新 • • 發佈:2018-04-01
文件內容 imp 運行時 margin OS 效果 輸出結果 wait stdout
1、文件進度條
代碼需求:
實現可視化,不斷增加#####的功能。
代碼實現:
1 #!/user/bin/env ptyhon 2 # -*- coding:utf-8 -*- 3 # Author: VisonWong 4 5 import sys,time 6 for i in range(20): 7 sys.stdout.write("#") 8 sys.stdout.flush() 9 time.sleep(0.2)
輸出結果:
1 E:\Python\PythonLearing\venv\Scripts\python.exe E:/Python/PythonLearing/進度條.py2 ####################
會有不斷增加#的動畫效果。
2、文件內容參數替換
代碼需求:
通過運行相應方法,輸入替換內容和被替換內容,實現文件內容的替換
1 #!/user/bin/env ptyhon 2 # -*- coding:utf-8 -*- 3 # Author: VisonWong 4 5 from sys import argv 6 7 script,find_str,replace_str = argv 8 9 f = open(‘yesterday.txt‘,‘r‘,encoding=‘utf-8‘) 10 f1 = open(‘yesterday_bak.txt‘,‘w‘,encoding=‘utf-8‘) 11 12 13 for line in f: 14 if find_str in line: 15 line = line.replace(find_str,replace_str) 16 f1.write(line) 17 18 f.close() 19 f1.close()
輸出結果:
運行時,在命令行輸入:
python changefile.py young old
原文件內容:
1 Oh, yesterday when I was young 2 噢 昨日當我年少輕狂3 So many, many songs were waiting to be sung 4 有那麽那麽多甜美的曲兒等我歌唱 5 So many wild pleasures lay in store for me 6 有那麽多肆意的快樂等我享受 7 And so much pain my eyes refused to see 8 還有那麽多痛苦 我的雙眼卻視而不見 9 There are so many songs in me that won‘t be sung 10 我有太多歌曲永遠不會被唱起 11 I feel the bitter taste of tears upon my tongue 12 我嘗到了舌尖淚水的苦澀滋味 13 The time has come for me to pay for yesterday 14 終於到了付出代價的時間 為了昨日 15 When I was young 16 當我年少輕狂
修改後文件內容:
1 Oh, yesterday when I was old 2 噢 昨日當我年少輕狂 3 So many, many songs were waiting to be sung 4 有那麽那麽多甜美的曲兒等我歌唱 5 So many wild pleasures lay in store for me 6 有那麽多肆意的快樂等我享受 7 And so much pain my eyes refused to see 8 還有那麽多痛苦 我的雙眼卻視而不見 9 There are so many songs in me that won‘t be sung 10 我有太多歌曲永遠不會被唱起 11 I feel the bitter taste of tears upon my tongue 12 我嘗到了舌尖淚水的苦澀滋味 13 The time has come for me to pay for yesterday 14 終於到了付出代價的時間 為了昨日 15 When I was old 16 當我年少輕狂
Python實踐之路4——實現進度條和文件內容參數替換