我正在使用下面的代码提取文件,如下所示,但我看到正在创建其他文件夹,有人可以帮助我为什么要创建额外的文件夹。
我的文件是abc.zip,其中包含文件sql.db,所以理想情况下我需要文件夹文件为abc / sql.db但是当我使用下面的代码提取时我得到文件夹为acb / abc / sql.db,为什么是我正在创建这个额外的文件夹
def unzip_artifact( local_directory, file_path ):
fileName, ext = os.path.splitext( file_path )
if ext == ".zip":
print 'unzipping file ' + basename(fileName) + ext
try:
with zipfile.ZipFile(file_path) as zf:
for member in zf.infolist():
# Path traversal defense copied from
# http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789
words = member.filename.split('/')
path = local_directory
for word in words[:-1]:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in (os.curdir, os.pardir, ''): continue
path = os.path.join(path, word)
zf.extract(member, path)
except zipfile.error, e:
print "Bad zipfile: %s" % (e)
return
答案 0 :(得分:0)
通常解压缩文件会为您创建目录。因此,如果.zip文件中包含abc目录,那么您构建的路径就会受到影响。尝试:
def unzip_artifact( local_directory, file_path ):
fileName, ext = os.path.splitext( file_path )
if ext == ".zip":
print 'unzipping file ' + basename(fileName) + ext
try:
with zipfile.ZipFile(file_path) as zf:
for member in zf.infolist():
# Path traversal defense copied from
# http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789
zf.extract(member, local_directory)
except zipfile.error, e:
print "Bad zipfile: %s" % (e)
return
或者更好,只需使用extractall:
def unzip_artifact( local_directory, file_path ):
fileName, ext = os.path.splitext( file_path )
if ext == ".zip":
print 'unzipping file ' + basename(fileName) + ext
try:
zipfile.ZipFile(file_path).extractall(local_directory)
except zipfile.error, e:
print "Bad zipfile: %s" % (e)
return