[英]How do I extract a file with the python zipfile library while changing it's name
这是由路径文件问题引起的(不幸的是,在我看来, 这并不正确)。
我有一个zipfile,我正尝试用python提取。 压缩文件似乎已在Windows上创建。 我必须从zip文件中提取文件的代码是这样的:
def unzip_file(zipfile_path):
z = zipfile.ZipFile(zipfile_path)
# get pathname without extension
directory = os.path.splitext(zipfile_path)[0]
print directory
if not os.path.exists(directory):
os.makedirs(directory)
#this line doesn't work. tries to extract "Foobar\\baz.quux" to directory and complains that the directory doesn't exist
# z.extractall(directory)
for name in z.namelist():
# actual dirname we want is this
# (dirname, filename) = os.path.split(name)
# I've tried to be cross-platform, (see above) but aparently zipfiles save filenames as
# Foobar\filename.log so I need this for cygwin
dir_and_filename = name.split('\\')
if len(dir_and_filename) >1:
dirname = dir_and_filename[0:-1]
filename = dir_and_filename[-1]
else:
dirname = ['']
filename = dir_and_filename[0]
out_dir = os.path.join(directory, *dirname)
print "Decompressing " + name + " on " + out_dir
if not os.path.exists(out_dir):
os.makedirs(out_dir)
z.extract(name, out_dir)
return directory
尽管这似乎过于复杂,但它是尝试解决我发现的一些错误。 zipfile的一个成员是Foobar\\\\filename.log
。 试图提取它抱怨该目录不存在。 我需要一种使用这样的方法的方法:
zipfile.extract_to(member_name, directory_name, file_name_to_write)
其中member name是要读取的成员的名称(在此示例中为Foobar\\\\filename.log
),directory_name是我们要写入的目录的名称,而file_name_to_write是我们要写入的文件的名称写(在本例中为filename.log
)。 似乎不支持此功能。 是否有人对如何获取提取具有嵌套表达式的zip存档的跨平台实现有其他想法?
根据此答案 ,我拥有的zipfile可能不符合zipfile规范(它表示:
为了与Amiga和UNIX文件系统等兼容,所有斜杠必须为正斜杠“ /”,而不是反斜杠“ \\”。
在zipfile规范 4.4.17中)如何解决此问题?
我通过简单地将其unzip
解决了这一问题。 我们需要检查退出代码为0或1,因为unzip
命令返回了退出代码1(由于unzip
格式错误,给出的消息类似于warning: zipfile appears to contain backslashes as path separators
。
#!/bin/bash
unzip $1 -d $2
exit_code=$?
# we catch exit_codes < 2 as the zipfiles are malformed
if [ $exit_code -lt 2 ]
then exit 0
else exit $exit_code
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.