在Python中优化内存使用的压缩文件夹
有没有办法在压缩一个包含多个文件的文件夹时减少内存使用?因为在处理大文件时,可能会消耗很多内存。如果有办法提高性能的话,我也很想知道。
import os
import zipfile
import errnodef
zip_folder(
zip_source_directory_target,
source_folder_to_zip_path,
zip_file_name,
logger: Logger,
compresslevel=6,
):
"""
do compression on a folder
"""
if os.path.exists(source_folder_to_zip_path) and os.path.exists(
zip_source_directory_target
):
full_zip_directory = os.path.join(zip_source_directory_target, zip_file_name)
with zipfile.ZipFile(
full_zip_directory,
"w",
compression=zipfile.ZIP_DEFLATED,
compresslevel=compresslevel,
) as zipf:
with os.scandir(source_folder_to_zip_path) as entries:
for entry in entries:
if entry.is_file():
arcname = os.path.relpath(entry.path, source_folder_to_zip_path)
zipf.write(entry.path, arcname=arcname)
else:
logger.warn(f"Zip source path: {zip_source_directory_target}")
raise FileNotFoundError(
errno.ENOENT,
os.strerror(errno.ENOENT),
f"Data folder path or zip source path may not exist please check",
)
编辑:感谢Mark Adler,之前提到的解决方案是有效的。第二次出现的问题是由于docker stats的内存检查不准确,这个是docker版本的问题。
1 个回答
0
使用 os.scandir
来代替 os.walk
。因为使用 os.walk
的时候,它会把整个文件夹的结构一次性加载到内存中,然后再去逐个查看。而 os.scandir
则会返回一个可以逐步查看文件夹内容的工具,它不会一次性把所有东西都放到内存里。