在Windows系统上解压缩包含非常长文件名的压缩文件时出错

时间:2013-12-11 13:12:11

标签: python python-2.7

在这里,我从Linux获得了一个压缩文件,现在我要解压缩Windows PC中的所有文件。但我得到一个错误,说文件名太长,无法写入系统。

现在我只知道在写入磁盘之前,首先我可以更改内存中的文件名,然后循环文件列表,将文件名更改为正确的文件名,然后将其写入磁盘。我怎样才能在Python中实现它?

zipfile 可以帮助我吗?我尝试编写一些代码来实现我的解决方案:

import os
import zipfile

if __name__ == "__main__":
    zf = zipfile.ZipFile('c://jekyll-export.zip', 'r')
    # before I extract to local directory,
    # how can I change the file name? 
    zf.extractall()  # this can not works

是的,我得到一个可行的版本!但任何人都可以提供更好的解决方案还是建议?

if __name__ == "__main__":
    try:
        zf = zipfile.ZipFile('c://jekyll-export.zip', 'r')
    except Exception as e:
        print str(e)
    i = 0
    try:
        for info in zf.infolist():
            i += 1
            print info.filename
            original_name = urllib.unquote(info.filename)
            print original_name
            out_path = os.path.join(os.path.dirname(__file__), 'output') + original_name
            print type(out_path)
            #print os.path.dirname(os.path.dirname(out_path))
            if not os.path.exists(os.path.dirname(out_path)):
                os.makedirs(os.path.dirname(out_path))
            buffer_size = 16 * 1024
            with zf.open(info) as fin, open(unicode(out_path, 'utf-8'), 'w') as fout:
                while True:
                    buf = fin.read(buffer_size)
                    if not buf:
                        break
                    fout.write(buf)
    except (WindowsError, IOError) as e:
        print str(e)

    print i

1 个答案:

答案 0 :(得分:1)

是的,但是你不会使用extract(保留原始文件名),而是使用openread手动解压缩:

with zipfile.ZipFile(path_to_zip) as zf:
    for info in zf.infolist():
        outpath = create the output path (original path is in info.filename)
        bufsiz = 16 * 1024 # or more to speed things up

        with zf.open(info) as fin, open(outpath, 'w') as fout:
            while True:
                buf = fin.read(bufsiz)
                if not buf:
                    break
                fout.write(buf)