import os
import string
import random
import zipfile
pool = string.ascii_lowercase + string.digits
root = 'outputForLab3'
count_file = 'filesize.txt'
zip_file = 'output3.zip'
file_size = 0
zip_size = 0
def random_select(k):
return ''.join(random.choices(pool, k=k))
print(pool)
if not os.path.exists(root):
os.mkdir(root)
for i in range(50):
rd = random_select(5)
with open(os.path.join(root, rd+'.txt'), 'w+') as f:
f.write(random_select(random.randint(10**3, 10**5)))
# pass
z = zipfile.ZipFile(zip_file, 'w')
with open(count_file, 'w+') as out:
for p, d, f in os.walk(root):
for file in f:
out.writelines(os.path.join(p, file)+' size:' +
str(os.path.getsize(os.path.join(p, file)))+'\n')
file_size += os.path.getsize(os.path.join(p, file))
z.write(os.path.join(p, file))
z.close()
zip_size = os.path.getsize(zip_file)
print(file_size, zip_size, file_size-zip_size, (file_size-zip_size)/file_size)
实验3完整代码,参考一下:
import os,random,string,zipfile
path= 'outputForLab3'
if not os.path.exists(path):
os.makedirs(path)
for i in range(50):
fn=''.join(random.sample(string.ascii_letters+string.digits,5))
with open(path+'/'+fn+'.txt','w',encoding='utf-8') as f:
n=random.choice(range(5,501))
for j in range(n):
f.writelines(''.join(random.sample(
string.ascii_letters+string.digits,random.randint(4,20))))
f.write('\n')
fpath=path+'/'+fn+'.txt'
with open('filesize.txt','a',encoding='utf-8') as f1:
con=fpath+'\t'+str(os.path.getsize(fpath))
f1.write(con+'\n')
with zipfile.ZipFile('output3.zip', mode='a') as zf:
zf.write(fpath, compress_type=zipfile.ZIP_DEFLATED)
size=0
with open('filesize.txt','r',encoding='utf-8') as f2:
line=[x for x in f2.read().strip().split('\n')]
for l in line:
size+=int(l.split('\t')[-1])
zf_size = os.path.getsize('output3.zip')
print(size,zf_size,size-zf_size,f'{zf_size/size*100}%')
输出结果:
F:\2021\qa\ot2>t9
165133 126374 38759 76.52861632744515%