补充一些有趣的知识
1. sys模块方法的补充,打印进度条
代码语言:javascript复制import sys,time
for i in range(20):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.1)
2. 实现简单的shell sed替换功能
代码语言:javascript复制import sys
res = sys.argv
print(res)
代码语言:javascript复制#命令行参数,在Terminal输入命令:python update_flie.py ,res接收到的结果为list,第一个元素是程序本身
将a.txt文件中所有的e替换为x
代码语言:javascript复制Hello everyone
Today is Saturday
代码: 执行命令: python update_file.py e x
代码语言:javascript复制import sys
find_str = sys.argv[1] #找到需要替换的字母,argv的第二个元素
replace_str = sys.argv[2] #替换成新的字母,argv的第三个元素
with open("a.txt", "r", encoding='utf-8') as f, open("b.txt", "w", encoding='utf-8') as fe:
for line in f:
if find_str in line:
line = line.replace(find_str, replace_str)
fe.write(line)
替换后b.txt文件:
代码语言:javascript复制Hxllo xvxryonx
Today is Saturday