我目前在使用Python的"extratall"函数进行解压缩,解压缩后还会创建一个文件夹,例如:myfile.zip -> myfile/myfile.zip。请问如何将其解压缩到当前文件夹而不是创建文件夹呢?是否有可能实现?
我目前在使用Python的"extratall"函数进行解压缩,解压缩后还会创建一个文件夹,例如:myfile.zip -> myfile/myfile.zip。请问如何将其解压缩到当前文件夹而不是创建文件夹呢?是否有可能实现?
我使用标准模块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')
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)
os.path.basename
来实现 - 我已经在我的答案中添加了它。 - John Zwinck
shutil.move
,指定源目录和目标(当前)目录,然后使用os.rmdir
删除您的临时目录。 - cs95