今日作业:
1、检索文件夹大小的程序,要求执行方式如下
python3.8 run.py 文件夹
import sys,os
src = sys.argv[1]
res = 0
def size_of_file(file):
global res
for file1 in os.listdir(r'%s'%file):
path = os.path.join(file,file1)
print(path)
if os.path.isfile(path):
res += os.path.getsize(src)
else:
size_of_file(path)
if os.path.isfile(r'%s'%src):
res = os.path.getsize(src)
else:
size_of_file(src)
print(res)
2、明天上午日考:随机验证码、模拟下载以及打印进度条、文件copy脚本
随机验证码
import random
def make_code(size=4):
res=''
for i in range(size):
s1=chr(random.randint(65,90))
s2=str(random.randint(0,9))
res+=random.choice([s1,s2])
return res
print(make_code())
import sys
print(sys.argv)
模拟下载以及打印进度条
import sys
import time
def progress(percent,width=50):
if percent >= 1:
percent=1
show_str=('[%%-%ds]' %width) %(int(width*percent)*'#')
print('
%s %d%%' %(show_str,int(100*percent)),file=sys.stdout,flush=True,end='')
#=========应用==========
data_size=102500
recv_size=0
while recv_size < data_size:
time.sleep(0.5) #模拟数据的传输延迟
recv_size+=1024 #每次收1024
percent=recv_size/data_size #接收的比例
progress(percent,width=70) #进度条的宽度70
文件copy脚本
import sys,time
def copy_file():
src_file=sys.argv[1]
dst_file=sys.argv[2]
start=time.time()
with open(f'{src_file}','rb') as f1,
open(f'{dst_file}','w') as f2:
for line in f1:
f2.write(line.decode('utf-8'))
else:
print('copy successfully')
end=time.time()
print('copy time %s'%(end-start))
copy_file()
# C:UsersSteadyDesktop练习
# python run.py C:UsersSteadyDesktop mp1.txt C:UsersSteadyDesktop mp2.txt