Khalsa Labs

Remove extra Mac files from pendrive with python

When copy files from mac to desktop a bunch of hidden files are generated in pendrive. you can easily remove extra Mac files from pendrive with python script. a little script is good enough to clean your pendrive/removable drive from extra Mac files.

Actually these are the files generated by Macintosh Operating System that are exists hidden and has same name starting from ‘._’ as original files. When you copy any file from mac to your pendrive, these files are copied with original files.

Here is a little Python script to remove extra mac files from Pendrive :

import os, shutil

path = raw_input("Enter your Pendrive path. e.g I:, j: ")
path = path + "\"

def remove_known_files(path):
    known_files = ['.DS_Store','.TemporaryItems','.fseventsd','.Spotlight-V100','.Trashes']
    new_known_files = []
    files = os.listdir(path)
    for f in files:
       if f.startswith("._") or f in known_files:
          new_known_files.append(f)
    for f in new_known_files:
       try:
           if os.path.isdir(path+f):
              shutil.rmtree(path+f)
       else:
           os.unlink(path+f)
       except:
           print "can't remove", path+f

def remove_mac_files(file_path, file_list):
    real_files = []
    temp_files = []
    # Filter real and fake files
    for f in file_list:
       if f.startswith('._'):
          temp_files.append(f.strip('._'))
       else:
          real_files.append(f)

    # match real and fake file names and delete matched
    for name in real_files:
       if name in temp_files:
           os.unlink(file_path+"\"+"._"+name)

remove_known_files(path)
drive_files = os.walk(path)

for dir_path, dirs, files in drive_files:
    file_list = os.listdir((dir_path))
    remove_mac_files(dir_path, file_list)

Above python script based on Python 2.7 (python 2.x) . you can download it from here

The following two tabs change content below.
Python Developer and DIY lover.

want to comment ??

Your email address will not be published. Required fields are marked *