3

次のような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を抽出したいのですが、どうすればよいですか?

4

2 に答える 2

3

extract または extractall を使用する代わりに、データを取得して任意のファイルに書き込みます。必要なことを行うコードサンプルを次に示します。

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 内のすべてのファイルを処理しますが、特定のファイルをチェックするために数行を簡単に追加できます。また、抽出されるファイルと同じ名前の作業ディレクトリ内のファイルを上書きします。

于 2013-04-18T23:00:19.787 に答える