Advertisement
caglartoklu

delete_thumbs_db.py

Apr 22nd, 2011
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """
  3. Ahh those pesky Thumbs.db files...
  4. This simple module removes them all from your disk.
  5. It also exposes a utility function get_file_list()
  6. that returns the full path of files that matches a list of patterns.
  7. Written by Caglar Toklu.
  8. """
  9.  
  10. import sys
  11. import os
  12. import fnmatch
  13.  
  14.  
  15. def get_file_list(top=".", lst_patterns=None):
  16.     """
  17.    Returns the file list starting from the specified directory top.
  18.    top is a string indicating the directory to start the search.
  19.    lst_patterns is a list of strings indicating patterns to select files.
  20.    Required imports:
  21.        import sys
  22.        import os
  23.        import fnmatch
  24.    """
  25.     if lst_patterns == None:
  26.         lst_patterns = ["*"]
  27.     lst_files_selected = []
  28.     for root, dirs, files in os.walk(top, topdown=False):
  29.         # The following exists only to use 'dirs' and make Pylint happy.
  30.         # It has absolutely no effect.
  31.         sys.stdout.write(str(type(dirs))[:0])
  32.  
  33.         for file_name in files:
  34.             full_file_name = os.path.join(root, file_name)
  35.             matched = False
  36.             for a_pattern in lst_patterns:
  37.                 if fnmatch.fnmatch(file_name, a_pattern):
  38.                     matched = True
  39.                     break
  40.             if matched:
  41.                 lst_files_selected.append(os.path.normpath(full_file_name))
  42.     return lst_files_selected
  43.  
  44.  
  45. def delete_thumbs_db_files():
  46.     """
  47.    Deletes all the thumbs.db files from your disk.
  48.    """
  49.     lst_patterns = ["thumbs.db"]
  50.     print "Building file list, please wait..."
  51.     lst_files_selected = get_file_list("/", lst_patterns)
  52.     print len(lst_files_selected), "found."
  53.     deleted = 0
  54.     failed = 0
  55.     for full_file_name in lst_files_selected:
  56.         try:
  57.             os.remove(full_file_name)
  58.             deleted = deleted + 1
  59.             print "OK:", full_file_name
  60.         except WindowsError:
  61.             print "FAIL:", full_file_name
  62.             failed = failed + 1
  63.         except:
  64.             print "FAIL:", full_file_name
  65.             failed = failed + 1
  66.     print deleted, "file(s) successfully deleted", failed, "failed."
  67.  
  68.  
  69. def main():
  70.     """
  71.    The entry point of the module.
  72.    """
  73.     delete_thumbs_db_files()
  74.  
  75. if __name__ == '__main__':
  76.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement