1、检索文件夹大小的程序,要求执行方式如下:
python3.8 run.py 文件夹
import sys
import os
file_path = sys.argv[1]
def my_get_size(file_path):
file_size = 0
if not os.path.exists(file_path):
print('你输入的文件路径不存在。')
return
if not os.path.isdir(file_path):
print('必须输入文件夹路径。')
return
for dir in os.listdir(file_path):
son_path = r'%s\%s'%(file_path,dir)
if os.path.isfile(son_path):
file_size += os.path.getsize(son_path)
else:
file_size += my_get_size(son_path)
return file_size
res = my_get_size(file_path)
print('该文件夹的大小为: {} 字节。'.format(res))
2、明天上午日考:随机验证码、模拟下载以及打印进度条、文件copy脚本
1)随机验证码
import random
def generate_code(n=4):
code = ''
for i in range(n):
s1 = chr(random.randint(65,90))
s2 = str(random.randint(0,9))
str1 = random.choice([s1,s2])
code += str1
return code
res = generate_code(6)
print(res)
2)模拟下载以及打印进度条
import time
def progress_bar(percent):
if percent>1:
percent = 1
str_num = int(50*percent)*'#'
print('
[%-50s]%s%%'%(str_num,int(percent*100)),end='')
download_size = 0
total_size = 1000000
while download_size < total_size:
time.sleep(0.01)
download_size += 1024
percent = download_size / total_size
progress_bar(percent)
3)文件copy脚本
import sys
src_file = sys.argv[1]
dst_file = sys.argv[2]
with open(r'%s'%src_file,'rb') as f1,
open(r'%s'%dst_file,'wb') as f2:
for line in f1:
f2.write(line)