LoginSignup
1
0

More than 5 years have passed since last update.

ディレクトリまるごとアーカイブ

Last updated at Posted at 2018-07-06

shutil を使おうよ,なんて言わないで.

背景

shutil.make_archive() を使うと,なぜかアーカイブのルートが'.'になってしまい,気に食わないのであった.
ちょっとぐぐっただけだと,ディレクトリまるごと操作は固めるのも消すのもshutilを使えって風潮に一石を投じる,などということはなく,自分が使い易いような関数を書いただけ.

src

短いので,多分ソースを見た方が圧倒的に早い.
https://github.com/hadacchi/archivedir

(7/7 修正)
個人的な好みにより,無圧縮zipになる.archivedir内のZIP_STOREDのとこを直せば圧縮されるはず.

--- a/archivedir/archivedir.py
+++ b/archivedir/archivedir.py
@@ -1,7 +1,7 @@
 from .listdir import listdirs,listfiles
 from os import remove, rmdir
 from os.path import isdir
-from zipfile import ZipFile, ZIP_STORED
+from zipfile import ZipFile, ZIP_STORED, ZIP_DEFLATED

 def archivedir(zipfilename,targetdir,mode='keep'):
     '''archive dir recursively
@@ -12,7 +12,7 @@ def archivedir(zipfilename,targetdir,mode='keep'):
     if not isdir(targetdir):
         raise Exception('No directory')
     flist = listfiles(targetdir)
-    with ZipFile(zipfilename,'w',ZIP_STORED) as zfile:
+    with ZipFile(zipfilename,'w',ZIP_DEFLATED) as zfile:
         for f in flist:
             zfile.write(f)
     if mode == 'remove':

ファイル名はソートされてなければならない!って人はarchivedirの14行目でsortedする.

--- a/archivedir/archivedir.py
+++ b/archivedir/archivedir.py
@@ -11,7 +11,7 @@ def archivedir(zipfilename,targetdir,mode='keep'):
     '''
     if not isdir(targetdir):
         raise Exception('No directory')
-    flist = listfiles(targetdir)
+    flist = sorted(listfiles(targetdir))
     with ZipFile(zipfilename,'w',ZIP_STORED) as zfile:
         for f in flist:
             zfile.write(f)

使い方

test.py がサンプルになっている.
簡単すぎて,ぐぅの音も出ない.

注意

アーカイブしたら消すオプションもつけてみた.
普通に消してくるので注意してね.

shutil.rmtree() を使おうよ,なんて言わないで.
圧縮まで書いた時点でほぼ必要なパーツは揃ってたから,ついでに書いた.

1
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0