在Python中解压文件

发布于 2024-09-13 17:19:31 字数 174 浏览 9 评论 0原文

我通读了 zipfile 文档,但无法阅读不了解如何解压缩文件,只了解如何压缩文件。如何将 zip 文件的所有内容解压缩到同一目录中?

I read through the zipfile documentation, but couldn't understand how to unzip a file, only how to zip a file. How do I unzip all the contents of a zip file into the same directory?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

软糯酥胸 2024-09-20 17:19:31
import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
    zip_ref.extractall(directory_to_extract_to)

差不多就这样了!

import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
    zip_ref.extractall(directory_to_extract_to)

That's pretty much it!

剧终人散尽 2024-09-20 17:19:31

如果您使用的是Python 3.2或更高版本:

import zipfile
with zipfile.ZipFile("file.zip","r") as zip_ref:
    zip_ref.extractall("targetdir")

您不需要对此使用closetry/catch,因为它使用
上下文管理器构建。

If you are using Python 3.2 or later:

import zipfile
with zipfile.ZipFile("file.zip","r") as zip_ref:
    zip_ref.extractall("targetdir")

You dont need to use the close or try/catch with this as it uses the
context manager construction.

雄赳赳气昂昂 2024-09-20 17:19:31

zipfile 是一个有点低级的库。除非您需要它提供的具体信息,否则您可以使用 shutil 的高级函数 make_archiveunpack_archive

make_archive 已在 this 答案中进行了描述。至于unpack_archive

import shutil
shutil.unpack_archive(filename, extract_dir)

unpack_archive自动从filename的“扩展名”中检测压缩格式(.zip,< code>.tar.gz 等),make_archive 也是如此。此外,filenameextract_dir可以是任何类路径对象(例如pathlib.Path实例)从 Python 3.7 开始。

zipfile is a somewhat low-level library. Unless you need the specifics that it provides, you can get away with shutil's higher-level functions make_archive and unpack_archive.

make_archive is already described in this answer. As for unpack_archive:

import shutil
shutil.unpack_archive(filename, extract_dir)

unpack_archive detects the compression format automatically from the "extension" of filename (.zip, .tar.gz, etc), and so does make_archive. Also, filename and extract_dir can be any path-like objects (e.g. pathlib.Path instances) since Python 3.7.

小帐篷 2024-09-20 17:19:31

如果您使用的是 Python 2.6+,请使用 extractall 方法

zip = ZipFile('file.zip')  # from zipfile import ZipFile
zip.extractall('target_dir')
zip.close()

Use the extractall method, if you're using Python 2.6+

zip = ZipFile('file.zip')  # from zipfile import ZipFile
zip.extractall('target_dir')
zip.close()
泅人 2024-09-20 17:19:31

您也可以仅导入ZipFile

from zipfile import ZipFile
zf = ZipFile('path_to_file/file.zip', 'r')
zf.extractall('path_to_extract_folder')
zf.close()

适用于Python 2Python 3

You can also import only ZipFile:

from zipfile import ZipFile
zf = ZipFile('path_to_file/file.zip', 'r')
zf.extractall('path_to_extract_folder')
zf.close()

Works in Python 2 and Python 3.

梦冥 2024-09-20 17:19:31

如果你想在 shell 中完成,而不是编写代码。

 python3 -m zipfile -e myfiles.zip myfiles/

myfiles.zip 是 zip 存档,myfiles 是解压文件的路径。

If you want to do it in shell, instead of writing code.

 python3 -m zipfile -e myfiles.zip myfiles/

myfiles.zip is the zip archive and myfiles is the path to extract the files.

塔塔猫 2024-09-20 17:19:31

试试这个:


import zipfile
def un_zipFiles(path):
    files=os.listdir(path)
    for file in files:
        if file.endswith('.zip'):
            filePath=path+'/'+file
            zip_file = zipfile.ZipFile(filePath)
            for names in zip_file.namelist():
                zip_file.extract(names,path)
            zip_file.close() 

path : 解压文件的路径

try this :


import zipfile
def un_zipFiles(path):
    files=os.listdir(path)
    for file in files:
        if file.endswith('.zip'):
            filePath=path+'/'+file
            zip_file = zipfile.ZipFile(filePath)
            for names in zip_file.namelist():
                zip_file.extract(names,path)
            zip_file.close() 

path : unzip file's path

酒几许 2024-09-20 17:19:31
from zipfile import ZipFile
ZipFile("YOURZIP.zip").extractall("YOUR_DESTINATION_DIRECTORY")

您将提取文件的目录之前不需要存在,此时您可以将其命名为

YOURZIP.zip(如果您的项目位于同一目录中),则该目录是 zip 的名称。
如果没有,请使用 PATH,即:C://....//YOURZIP.zip

考虑通过 PATH 中的其他 / 转义 /
如果您权限被拒绝,请尝试以管理员身份启动 IDE(即:Anaconda),

YOUR_DESTINATION_DIRECTORY 将在与您的项目相同的目录中创建

from zipfile import ZipFile
ZipFile("YOURZIP.zip").extractall("YOUR_DESTINATION_DIRECTORY")

The directory where you will extract your files doesn't need to exist before, you name it at this moment

YOURZIP.zip is the name of the zip if your project is in the same directory.
If not, use the PATH i.e : C://....//YOURZIP.zip

Think to escape the / by an other / in the PATH
If you have a permission denied try to launch your ide (i.e: Anaconda) as administrator

YOUR_DESTINATION_DIRECTORY will be created in the same directory than your project

_畞蕅 2024-09-20 17:19:31
import os 
zip_file_path = "C:\AA\BB"
file_list = os.listdir(path)
abs_path = []
for a in file_list:
    x = zip_file_path+'\\'+a
    print x
    abs_path.append(x)
for f in abs_path:
    zip=zipfile.ZipFile(f)
    zip.extractall(zip_file_path)

如果文件不是 zip,则不包含对该文件的验证。如果文件夹包含非 .zip 文件,则会失败。

import os 
zip_file_path = "C:\AA\BB"
file_list = os.listdir(path)
abs_path = []
for a in file_list:
    x = zip_file_path+'\\'+a
    print x
    abs_path.append(x)
for f in abs_path:
    zip=zipfile.ZipFile(f)
    zip.extractall(zip_file_path)

This does not contain validation for the file if its not zip. If the folder contains non .zip file it will fail.

安人多梦 2024-09-20 17:19:31

正如此处所述,zipfile 目前不支持符号链接。如果需要使用符号链接解压,可以调用unzip

import subprocess

def unzip(zip_path: str, dir_path: str):
  # python's `zipfile` module lacks symlink support
  #   https://github.com/python/cpython/issues/82102
  cmd = ['unzip', '-o', zip_path, '-d', dir_path]
  proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  if proc.returncode:
    cmd_str = "'" + "' '".join(cmd) + "'"
    raise Exception(
      f"Unzip command ({cmd_str}) failed with exit code of "
      f"{proc.returncode} and output of:\n{proc.stdout.decode()}"
    )

As mentioned here, zipfile does not currently support symlinks. If you need to extract with symlinks, you can call unzip:

import subprocess

def unzip(zip_path: str, dir_path: str):
  # python's `zipfile` module lacks symlink support
  #   https://github.com/python/cpython/issues/82102
  cmd = ['unzip', '-o', zip_path, '-d', dir_path]
  proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  if proc.returncode:
    cmd_str = "'" + "' '".join(cmd) + "'"
    raise Exception(
      f"Unzip command ({cmd_str}) failed with exit code of "
      f"{proc.returncode} and output of:\n{proc.stdout.decode()}"
    )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文