ZipFile 提取后获取本地文件名()
Get Local File name after ZipFile extract()
ZipFile extract()
运行后如何获取本地文件名?
当我这样做时:
with zipfile.ZipFile(localZipFilePath, "r") as zf:
for name in zf.namelist():
localFilePath = zf.extract(name, '/tmp/')
print localFilePath
zip 文件中的文件是:src/xyz/somefile.txt
localFilePath
输出:/tmp/src
这里写的文件:/tmp/src/xyz/somefile.txt
这就是我想以某种优雅的方式获得的文件。
我想你误会了什么。 ZipFile.extract()
method 始终 returns 完整 目录路径或它为特定 zipfile 成员创建的文件的路径。
文档没有明确说明这一点,source code for the method 在这里很清楚:
if member.filename[-1] == '/':
if not os.path.isdir(targetpath):
os.mkdir(targetpath)
return targetpath
with self.open(member, pwd=pwd) as source, \
file(targetpath, "wb") as target:
shutil.copyfileobj(source, target)
return targetpath
因此,要么成员文件名以 /
(一个目录)结尾,在这种情况下创建目录,要么创建一个文件,其中包含复制的数据。无论哪种方式,targetpath
是刚刚创建的文件系统条目的本地路径。
我已经 opened a Python issue 更新了文档;自 2015-03-15 起,文档已更新为:
Returns the normalized path created (a directory or new file).
根本问题是我没有考虑到文件夹是 zip 文件的一部分。我的代码仅设计用于处理文件。
我通过添加 if 语句来检测文件夹来修复我的代码:
with zipfile.ZipFile(localZipFilePath, "r") as zf:
for name in zf.namelist():
localFilePath = zf.extract(name, '/tmp/')
if os.path.isdir(localFilePath):
continue
print localFilePath
ZipFile extract()
运行后如何获取本地文件名?
当我这样做时:
with zipfile.ZipFile(localZipFilePath, "r") as zf:
for name in zf.namelist():
localFilePath = zf.extract(name, '/tmp/')
print localFilePath
zip 文件中的文件是:src/xyz/somefile.txt
localFilePath
输出:/tmp/src
这里写的文件:/tmp/src/xyz/somefile.txt
这就是我想以某种优雅的方式获得的文件。
我想你误会了什么。 ZipFile.extract()
method 始终 returns 完整 目录路径或它为特定 zipfile 成员创建的文件的路径。
文档没有明确说明这一点,source code for the method 在这里很清楚:
if member.filename[-1] == '/':
if not os.path.isdir(targetpath):
os.mkdir(targetpath)
return targetpath
with self.open(member, pwd=pwd) as source, \
file(targetpath, "wb") as target:
shutil.copyfileobj(source, target)
return targetpath
因此,要么成员文件名以 /
(一个目录)结尾,在这种情况下创建目录,要么创建一个文件,其中包含复制的数据。无论哪种方式,targetpath
是刚刚创建的文件系统条目的本地路径。
我已经 opened a Python issue 更新了文档;自 2015-03-15 起,文档已更新为:
Returns the normalized path created (a directory or new file).
根本问题是我没有考虑到文件夹是 zip 文件的一部分。我的代码仅设计用于处理文件。
我通过添加 if 语句来检测文件夹来修复我的代码:
with zipfile.ZipFile(localZipFilePath, "r") as zf:
for name in zf.namelist():
localFilePath = zf.extract(name, '/tmp/')
if os.path.isdir(localFilePath):
continue
print localFilePath