Pythonのzipfileライブラリを使用していますか?

Pythonのzipfileライブラリを使用していますか?

file.txtにファイルを追加したいとしましょう。foo.zipこれを行うことができます。zip -u foo.zip file.txt

foo.zip/very/many/paths/ただし、zipファイル内に(zipファイルに基づく)パスがあるフォルダがすでにあります。

file.txtzipファイル内の場所になるようにzipファイルにどのように追加しますかfoo.zip/very/many/paths/file.txt

必要なディレクトリ構造を最初に作成することもできますが、より簡単な方法はありませんか?

私は通常そうします:

$ls
ファイル.txt
foo.zip
$mkdir 非常に
$ mkdir 非常に/たくさん
$ mkdir 非常に/多/パス
$ cp file.txt 非常に/多数/パス
$zip -u foo.zip 非常に/多/パス/file.txt
$rm -rf 非常に

ベストアンサー1

Pythonのzipfileライブラリを使用していますか?

~/wrk/tmp$ ls test.zip
ls: cannot access test.zip: No such file or directory

わかりました、「test.zip」はありません...

~/wrk/tmp$ python -c 'import zipfile,sys ; zipfile.ZipFile(sys.argv[1],"a").write(sys.a
rgv[2],sys.argv[3])' test.zip /etc/motd text/motd

存在しないzipファイルに「/ etc / motd」を「text / motd」として追加しましょう...

~/wrk/tmp$ ls -l test.zip 
-rw-r--r-- 1 yeti yeti 473 Mar 23 09:51 test.zip

zipfileライブラリは「test.zip」を生成するのに十分です。

~/wrk/tmp$ unzip -lv test.zip 
Archive:  test.zip
 Length   Method    Size  Cmpr    Date    Time   CRC-32   Name
--------  ------  ------- ---- ---------- ----- --------  ----
     357  Stored      357   0% 2014-03-20 15:47 ff1b8b7f  text/motd
--------          -------  ---                            -------
     357              357   0%                            1 file

..私が望む内容が含まれているようですが..

標準出力で解凍して確認してみましょう...

~/wrk/tmp$ unzip -p test.zip text/motd
Linux aurora 3.2.0-0.bpo.4-amd64 #1 SMP Debian 3.2.54-2~bpo60+1 x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.

美しい!

次に、2番目のファイルを追加します。

~/wrk/tmp$ python -c 'import zipfile,sys ; zipfile.ZipFile(sys.argv[1],"a").write(sys.argv[2],sys.argv[3])' test.zip /etc/issue otherdir/issue
~/wrk/tmp$ ls -l test.zip 
-rw-r--r-- 1 yeti yeti 605 Mar 23 09:52 test.zip
(yeti@aurora:1)~/wrk/tmp$ unzip -lv test.zip 
Archive:  test.zip
 Length   Method    Size  Cmpr    Date    Time   CRC-32   Name
--------  ------  ------- ---- ---------- ----- --------  ----
     357  Stored      357   0% 2014-03-20 15:47 ff1b8b7f  text/motd
      28  Stored       28   0% 2012-09-21 22:52 f9c3990c  otherdir/issue
--------          -------  ---                            -------
     385              385   0%                            2 files
~/wrk/tmp$ unzip -p test.zip otherdir/issue                                            Debian GNU/Linux 6.0 \n \l

~/wrk/tmp$ _

おすすめ記事