【问题标题】:Python: Unzip a file to current working directory but not maintain directory structure in zipPython:将文件解压缩到当前工作目录,但不在 zip 中维护目录结构
【发布时间】:2013-04-18 22:38:42
【问题描述】:

我有一个这样的 zip 文件:

myArchive.zip
|
-folder1
   |
   --folder2
        |
        ---myimage.jpg

当我尝试提取 myimage.jpg 时:

with zipfile.ZipFile('myArchive.zip', 'r') as zfile:
   zfile.extract('folder1/folder2/myimage.jpg')

我将在我当前的工作目录中获得 /folder1/folder2/myimage.jpg

但我只想将 myimage.jpg 提取到当前工作目录,我该怎么做?

【问题讨论】:

    标签: python zipfile


    【解决方案1】:

    非常简单的解决方案或多或少是这样的:

    with zipfile.ZipFile('myArchive.zip', 'r') as zfile:
        unpacked = open('myimage.jpg', 'w')
        unpacked.write(zfile.read('folder1/folder2/myimage.jpg'))
        unpacked.close()
    

    【讨论】:

    • 优秀;有时需要解码以将字节转换为字符串unpacked.write(zf.read(fn).decode('utf-8'))
    【解决方案2】:

    不要使用提取或提取全部,只需获取数据并将其写入您喜欢的任何文件即可。这是一个可以满足您需求的代码示例:

    import os, sys, time
    import zipfile
    
    ENC = 'cp437'
    outdir = unicode(os.path.abspath('.'))
    outzip = 'c:/1temp/timbersales.zip'
    zf = zipfile.ZipFile(outzip, 'r')
    
    
    for info in zf.infolist():
        fn, dtz = info.filename, info.date_time # , info.file_size
    
        # some zips have dirs listed as files. Catch
        # and bypass those.
        name = os.path.basename(fn)
        if not name:
            continue
    
        # get our filename converted from bytes to unicode
        fn_uni = fn.decode(ENC, 'replace')
        bn_uni = os.path.basename(fn_uni)
    
    
        # this method is about 15% faster than extractall, and 
        # preserves modify and access dates
        c = zf.open(fn)
        outfile = os.path.join(outdir, bn_uni)
    
        # try/except to avoid problems with locked files, etc
        # do in chunks to avoid memory problems
        chunk = 2**16
        try:
            with open(outfile, 'wb') as f:
                s = c.read(chunk)
                f.write(s)
                while not len(s) < chunk: 
                    s = c.read(chunk)
                    f.write(s)
            c.close()
            # set modify and access dates to that inside the zip
            dtout = time.mktime(dtz + (0, 0, -1))
            os.utime(outfile, (dtout, dtout))
        except IOError:
            c.close()
    

    此示例执行 zip 中的所有文件,但您可以轻松添加几行来检查特定文件。它还将覆盖工作目录中与被提取文件同名的所有文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 2011-12-16
      • 2016-08-11
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多