使用Python解压不带文件夹的zip文件

4

我目前在使用Python的"extratall"函数进行解压缩,解压缩后还会创建一个文件夹,例如:myfile.zip -> myfile/myfile.zip。请问如何将其解压缩到当前文件夹而不是创建文件夹呢?是否有可能实现?


我建议使用 shutil.move,指定源目录和目标(当前)目录,然后使用 os.rmdir 删除您的临时目录。 - cs95
这个回答解决了你的问题吗?[使用Python ZipFile从zip文件中提取文件而不保留结构?] (https://dev59.com/aW445IYBdhLWcg3wUoxe) - Boketto
2个回答

1

我使用标准模块zipfile。这里有一个方法extract,它提供了我认为你想要的功能。该方法具有可选参数path,可以将内容提取到当前工作目录或给定路径。

import os, zipfile

os.chdir('path/of/my.zip')

with zipfile.ZipFile('my.zip') as Z :
    for elem in Z.namelist() :
        Z.extract(elem, 'path/where/extract/to')

如果省略 'path/where/extract/to',则ZIP文件中的文件将被提取到ZIP文件所在的目录中。

当我使用extract()方法时,它仍会提取文件夹。 - Boketto

0
import shutil

# loop over everything in the zip
for name in myzip.namelist():
    # open the entry so we can copy it
    member = myzip.open(name)
    with open(os.path.basename(name), 'wb') as outfile:
        # copy it directly to the output directory,
        # without creating the intermediate directory
        shutil.copyfileobj(member, outfile)

请在您的答案中添加解释。 - heinst
欢迎来到 Stack Overflow @heinst。幸运的是,Joris 已经对代码添加了一些注释,所以你可以跟着走。 - John Zwinck
1
你说的“欢迎来到Stack Overflow”是什么意思?我在版主队列里,没有任何评论,所以我请你发表一些评论。不必这么粗鲁啊。 - heinst
@JohnZwinck,目前myzip.namelist()返回的是类似于{folder1/file1.txt,folder1/fil2.txt,folder1/file3.txt}这样的内容,我该如何只返回{file1.txt,file2.txt,fil3.txt}而不带文件夹路径? - Brook Gebremedhin
@BrookGebremedhin:你可以使用os.path.basename来实现 - 我已经在我的答案中添加了它。 - John Zwinck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接