在Python中解压文件
我通读了 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
差不多就这样了!
That's pretty much it!
如果您使用的是Python 3.2或更高版本:
您不需要对此使用close或try/catch,因为它使用
上下文管理器构建。
If you are using Python 3.2 or later:
You dont need to use the close or try/catch with this as it uses the
context manager construction.
zipfile
是一个有点低级的库。除非您需要它提供的具体信息,否则您可以使用shutil
的高级函数make_archive
和
unpack_archive
。make_archive
已在 this 答案中进行了描述。至于unpack_archive
:unpack_archive
自动从filename
的“扩展名”中检测压缩格式(.zip
,< code>.tar.gz 等),make_archive
也是如此。此外,filename
和extract_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 withshutil
's higher-level functionsmake_archive
andunpack_archive
.make_archive
is already described in this answer. As forunpack_archive
:unpack_archive
detects the compression format automatically from the "extension" offilename
(.zip
,.tar.gz
, etc), and so doesmake_archive
. Also,filename
andextract_dir
can be any path-like objects (e.g. pathlib.Path instances) since Python 3.7.如果您使用的是 Python 2.6+,请使用
extractall
方法Use the
extractall
method, if you're using Python 2.6+您也可以仅导入
ZipFile
:适用于Python 2和Python 3。
You can also import only
ZipFile
:Works in Python 2 and Python 3.
如果你想在 shell 中完成,而不是编写代码。
myfiles.zip
是 zip 存档,myfiles
是解压文件的路径。If you want to do it in shell, instead of writing code.
myfiles.zip
is the zip archive andmyfiles
is the path to extract the files.试试这个:
path : 解压文件的路径
try this :
path : unzip file's path
您将提取文件的目录之前不需要存在,此时您可以将其命名为
YOURZIP.zip(如果您的项目位于同一目录中),则该目录是 zip 的名称。
如果没有,请使用 PATH,即:C://....//YOURZIP.zip
考虑通过 PATH 中的其他
/
转义/
如果您
权限被拒绝
,请尝试以管理员身份启动 IDE(即:Anaconda),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 PATHIf you have a
permission denied
try to launch your ide (i.e: Anaconda) as administratorYOUR_DESTINATION_DIRECTORY will be created in the same directory than your project
如果文件不是 zip,则不包含对该文件的验证。如果文件夹包含非 .zip 文件,则会失败。
This does not contain validation for the file if its not zip. If the folder contains non .zip file it will fail.
正如此处所述,
zipfile
目前不支持符号链接。如果需要使用符号链接解压,可以调用unzip
:As mentioned here,
zipfile
does not currently support symlinks. If you need to extract with symlinks, you can callunzip
: