如何使用Python压缩目录中特定类型的文件?

relj7zay  于 2023-11-20  发布在  Python
关注(0)|答案(2)|浏览(123)
  1. files = [os.listdir]
  2. files_to_zip = []
  3. for file in files:
  4. if str(file).__contains__("png"):
  5. files_to_zip.append(file)
  6. shutil.make_archive("test", 'zip', files_to_zip)

字符串
我的代码如上所述。我知道它不应该工作,但我真的想了解背后的逻辑。我想在当前目录中的所有 *.png文件的zip存档,然后将它们全部删除。现在我可以制作一个包含目录中所有文件的zip文件,但我只想要png文件。提前感谢。

dfddblmv

dfddblmv1#

我认为pathlib模块更容易使用。

  1. from pathlib import Path
  2. directory = <YOUR DIRECTORY>
  3. shutil.make_archive("test", 'zip', Path(directory).glob('*.png'))

字符串

xkftehaa

xkftehaa2#

  1. import os import shutil from unittest.mock import patch
  2. _os_path_isfile = os.path.isfile
  3. def accept(path):
  4. file_name, file_extension = os.path.splitext(path)
  5. if file_extension not in [".py", ".ipynb"]:
  6. return False
  7. print("archiving %r" % path)
  8. return _os_path_isfile(path)
  9. with patch("os.path.isfile", side_effect=accept):
  10. shutil.make_archive("archive_file_name", "zip", ".")

字符串

相关问题