解压缩zip文件而不使用文件夹python

解压缩zip文件而不使用文件夹python,python,Python,我目前正在使用python中的extratall函数来解压,解压后它还会创建一个文件夹,如:myfile.zip->myfile/myfile.zip,如何摆脱myfile flder并将其解压到当前文件夹,而不使用该文件夹,是否可能?我使用标准模块zipfile。有一种方法extract,它提供了我认为您需要的内容。此方法具有可选参数path,用于将内容提取到当前工作目录或给定路径 import shutil # loop over everything in the zip for nam

我目前正在使用python中的extratall函数来解压,解压后它还会创建一个文件夹,如:myfile.zip->myfile/myfile.zip,如何摆脱myfile flder并将其解压到当前文件夹,而不使用该文件夹,是否可能?

我使用标准模块
zipfile
。有一种方法
extract
,它提供了我认为您需要的内容。此方法具有可选参数
path
,用于将内容提取到当前工作目录或给定路径

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)
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文件的目录。

我建议使用
shutil.move
,指定源目录和目标(当前),然后
os.rmdir
删除临时目录。请在回答中添加说明欢迎使用Stack Overflow@heinst。幸运的是Joris已经在代码中添加了一些注释,所以您可以继续。欢迎使用堆栈溢出是什么意思?我在主持人队列中,没有任何评论,所以我请你发表一些评论。不要太粗鲁man@JohnZwinck,当前myzip.namelist()返回类似于{folder1/file1.txt、folder1/fil2.txt、folder1/file3.txt}的内容,我怎么能只返回类似于{file1.txt、file2.txt、fil3.txt}的内容而不返回文件夹目录呢?@brookebremedhin:您使用
os.path.basename
来实现这一点-我把它添加到了我的答案中。