0

したがって、 NamedTemporaryFile 関数によって指定された一時ディレクトリにいくつかのファイルを作成します。

zf = zipfile.ZipFile( zipPath, mode='w' )
for file in files:
    with NamedTemporaryFile(mode='w+b', bufsize=-1, prefix='tmp') as tempFile:
       tempPath = tempFile.name
    with open(tempPath, 'w') as f:
       write stuff to tempPath with contents of the variable 'file'
    zf.write(tempPath)

zf.close()

これらのファイルのパスを使用して zip ファイルに追加すると、一時ディレクトリ自体が圧縮されます。
解凍しようとすると、最終的に必要なファイルを含む一連の一時フォルダーが表示されます。
(つまり、AppData を含む user_id フォルダーを含むフォルダー Users を取得します...)。

フォルダーなしでファイルを直接追加して、解凍したときにファイルを直接取得する方法はありますか? どうもありがとう!

4

2 に答える 2

2

アークネームを付けてみてください:

from os import path

zf = zipfile.ZipFile( zipPath, mode='w' )
for file in files:
    with NamedTemporaryFile(mode='w+b', bufsize=-1, prefix='tmp') as tempFile:
       tempPath = tempFile.name
    with open(tempPath, 'w') as f:
       write stuff to tempPath with contents of the variable 'file'
    zf.write(tempPath,arcname=path.basename(tempPath))

zf.close()

を使用os.path.basenameすると、パスからファイルの名前を取得できます。zipfileのドキュメントによると、arcname のデフォルト値は、ドライブ文字がなく、先頭のパス セパレータが削除されたファイル名です。

于 2012-08-01T12:31:50.107 に答える
1

arcnameパラメータを使用してみてくださいzf.write

zf.write(tempPath, arcname='Users/mrb0/Documents/things.txt')

あなたのプログラムについて詳しく知らarcnameなくてfileも、tempPath.

于 2012-08-01T12:29:46.993 に答える