LoginSignup
2
5

More than 5 years have passed since last update.

Macで作られる._DS_Storeや._*ファイルをもろもろ削除するpythonスクリプト

Last updated at Posted at 2017-02-04

使い道

ポータブルHDDやUSBメモリーをMacに接続した後にWindowsやLinuxに接続すると、
.DS_Storeや既存ファイルのメタファイルっぽい._[既存ファイル名]達が大量に作られているのに気づく。
このファイル達はファイルシステムのセクタサイズより小さいため、数千ファイルあると数GB無駄になったりしていまう。まさに、そうなっていた。

Linuxであればfind . -name "._*" -exec rm -f {} \; などで削除できそうだが、
Windowsのexplorerで.*で検索して削除しようとしても、.*ではない普通のファイルやディレクトリが引っかかってしまい非常に削除しにくい。

そこで困っている人と自分向けに簡単にpythonでスクリプトを組んでみた。
なお、厳密なファイルチェックなどは行っていないので消えてはいけないファイルが消える可能性もゼロではないため、このスクリプトのご利用は自己責任でお願いします。

import os
import sys
import shutil

def deldirs(baseDir):
  print "Start " + baseDir
  ds = [baseDir]
  while True:
    if len(ds) == 0:
      print "Finished!!"
      break
    # Pop next target dir
    d = ds.pop(0)
    # Delete file
    fs = os.listdir(d)
    for fn in fs:
      fp = d + "/" +fn
      if fn[:2] == "._" or fn == ".DS_Store":
        if os.path.isfile(fp):
          print "Del File " + fp
          os.remove(fp)
      #elif os.path.isdir(fp):
      #    print "Del Dir " + fp
      #    shutil.rmtree(fp)

if __name__ == "__main__":
  if len(sys.argv) != 2:
    print "Usage: delmacfile.py TARGET_DIR"
    exit(1)
  baseDir = sys.argv[1]
  if os.path.isdir(baseDir) == False:
    print "Please arg1 is a TAGET_DIR"
    exit(2)
  deldirs(baseDir)

Windowsコマンドでやる方法もありそうだがPython好き向けということで。

2
5
0

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
2
5