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:PythonPythonLearingvenvScriptspython.exe E:/Python/PythonLearing/进度条.py 2 ####################
会有不断增加#的动画效果。
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 当我年少轻狂