使用Python将多个包含文件的文件夹压缩成一个zip包
我有一个这样的文件夹结构:
Parent folder
Folder1
1.txt
2.msg
...
Folder2
1.txt
2.py
...
我现在的方法是使用shutil.make_archive来压缩父文件夹(比如:13_03_2024.zip)。
问题是解压的时候显示的是
父文件夹 >> folder1, folder2
我希望的结果是只显示folder1和folder2。
有人能帮我解决这个问题吗?提前谢谢大家!!
2 个回答
0
在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在另一个地方使用这些数据。这个过程就像是把水从一个水桶倒到另一个水桶里。
当我们说到“数据流”,其实就是指这些数据在不同地方之间的移动。想象一下,你在厨房里做饭,可能需要从冰箱拿出食材,然后把它们放到锅里。这就像是数据从一个地方流向另一个地方。
有时候,数据在流动的过程中可能会遇到一些问题,比如数据不完整或者格式不对。这就像你在厨房里发现食材坏掉了,或者锅不够大,不能放下所有的食材一样。
为了让数据流动得更顺畅,我们可以使用一些工具和方法来帮助我们处理这些数据,就像在厨房里使用刀具、锅具来帮助我们做饭一样。
总之,理解数据流动的过程,可以帮助我们更好地管理和使用数据,让我们的编程工作更加高效。
import glob
import os
import zipfile
def remove_parent_path(parent_path, file_path):
# Get the relative path of the file_path with respect to the parent_path
relative_path = os.path.relpath(file_path, parent_path)
return relative_path
def compress_to(parent_path, out_file_path, structured_files=None, include_parent_dir=False):
with zipfile.ZipFile(out_file_path, 'w') as zipf:
for file in structured_files:
if not include_parent_dir:
zip_archive_name = remove_parent_path(parent_path, file)
else:
zip_archive_name = file
zipf.write(file, zip_archive_name)
if __name__ == '__main__':
parent_dir = 'out'
files_with_sub_dir = os.path.join(parent_dir, '*', '*.*')
out_file_path = 'sample.zip'`enter code here`
files_list = glob.glob(files_with_sub_dir, recursive=True)
compress_to(parent_dir, out_file_path, files_list, include_parent_dir=True)
0
我手动在下载文件夹里创建了一个叫'test'的文件夹,并添加了你的结构。
import shutil
shutil.make_archive(
base_name = '13_03_2024',
format = 'zip',
root_dir = 'test/',
base_dir = '.'
)
运行这个代码后,我成功地通过选择“在此解压...”来解压,没有父文件夹。
也可以通过shutil来解压:
import shutil
shutil.unpack_archive(
filename = '13_03_2024.zip',
extract_dir = '.',
format = 'zip')