一、压缩文件:使用zipfile和os
1、压缩单个文件
import zipfile
import os
zf = zipfile.ZipFile('datasets/train_catvnoncat_h5.zip', mode='w')
zf.write('datasets/train_catvnoncat.h5')
zf.write('datasets/test_catvnoncat.h5')
zf.close()
#os.remove('datasets/train_catvnoncat_h5.zip') # cleanup
2、批量压缩
import zipfile
import os
zf = zipfile.ZipFile('images/images_for_week3.zip', mode='w')
for i in range(120):
current_image_name = "%04d"%(i+1)+'.jpg'
zf.write('images/'+current_image_name)
zf.close()
os.remove('images/images_for_week3.zip') # cleanup
3、压缩整个文件夹
import zipfile
import os
z = zipfile.ZipFile('weights.zip',mode='w') #指定压缩后文件的路径
startdir = "weights"
for dirpath, dirnames, filenames in os.walk(startdir):
for filename in filenames:
z.write(os.path.join(dirpath, filename))
z.close()
os.remove('weights.zip')
二、移动文件:使用shutil和os
import os
import shutil # 用于移动、复制、打包、压缩、解压文件及文件夹
destination_path = 'C:\\Users\\a\\AppData\\Roaming\\nltk_data\\corpora\\treebank\\combined'
startdir = 'mydata/wsj'
for dirpath, dirnames, filenames in os.walk(startdir):
for filename in filenames:
source_path = os.path.join(dirpath, filename)
shutil.move(source_path, destination_path)
关于shutil模块的更多功能,推荐一个不错的博文:Python——shutil模块