ファイルを圧縮するtarfileモジュール

Pythonでのtarfileモジュールの使用方法を学んだのでメモしておく。
とりあえずLinuxで。

  • 複数のファイルをtarして、圧縮(gzかbz2)する。

make_tar.pyを以下のように作成する。

#!/usr/bin/env python
import tarfile
import time

files = ['calc_sub.f', 'calc_test.f']   #圧縮するファイル群
tar_file = tarfile.open('temp.tar.bz2', 'w:bz2') # bz2はgzとしてもよい。

for file in files:
    tar_file.add(file)

# 作成された圧縮ファイルをチェックする
members = tar_file.getmembers()
for info in members:
    print '%s: size=%d, mode=%s, mtime=%s' %\
          (info.name, info.size, info.mode,
           time.strftime('%Y.%m.%d', time.gmtime(info.mtime)))

実行結果

hoge@debian0:~/Python/tarfile$ ls -al
合計 20
drwxr-xr-x 2 hoge hoge 4096 2009-09-28 20:10 ./
drwxr-xr-x 4 hoge hoge 4096 2009-09-28 20:10 ../
-rw-r--r-- 1 hoge hoge  440 2009-09-28 20:10 calc_sub.f
-rw-r--r-- 1 hoge hoge  707 2009-09-28 20:10 calc_test.f
-rw-r--r-- 1 hoge hoge  388 2009-09-28 20:10 make_tar.py
hoge@debian0:~/Python/tarfile$ python make_tar.py 
calc_sub.f: size=440, mode=33188, mtime=2009.09.28
calc_test.f: size=707, mode=33188, mtime=2009.09.28
hoge@debian0:~/Python/tarfile$ ls -al
合計 24
drwxr-xr-x 2 hoge hoge 4096 2009-09-28 20:10 ./
drwxr-xr-x 4 hoge hoge 4096 2009-09-28 20:10 ../
-rw-r--r-- 1 hoge hoge  440 2009-09-28 20:10 calc_sub.f
-rw-r--r-- 1 hoge hoge  707 2009-09-28 20:10 calc_test.f
-rw-r--r-- 1 hoge hoge  388 2009-09-28 20:10 make_tar.py
-rw-r--r-- 1 hoge hoge  562 2009-09-28 20:10 temp.tar.bz2
hoge@debian0:~/Python/tarfile$ 

うまくいった。

参考:Python Scripting for Computational Science (Texts in Computational Science and Engineering), 8.3.4