Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. import os
  2. import argparse
  3.  
  4. file_stats = []
  5.  
  6. parser = argparse.ArgumentParser(description = 'Automatically sort media from a directory into folders by media type in another directory.')
  7. parser.add_argument('--source', required = True, help = 'The absolute path of the source directory containing files to be sorted.')
  8. parser.add_argument('--destination', required = True, help = 'An empty destination directory.')
  9. args = parser.parse_args()
  10.  
  11. if not os.path.isdir(args.source):
  12. exit('Source is not a directory')
  13.  
  14. if not os.path.isdir(args.destination):
  15. exit('Destination is not a directory')
  16.  
  17. def file_category(extension: str):
  18. extension = extension.lower()
  19. images = ['.jpg', '.png', '.gif', '.bmp', '.webp']
  20. videos = ['.mp4', '.3gp', '.webm']
  21. if extension in images:
  22. return "images"
  23. elif extension in videos:
  24. return "videos"
  25. else:
  26. return False
  27.  
  28. for root, dirs, files in os.walk(args.source):
  29.  
  30. for name in files:
  31. filepath = os.path.join(root, name)
  32. existing_file = next((item for item in file_stats if item['name'] == name), False)
  33. size = os.path.getsize(filepath)
  34. filename, file_extension = os.path.split(name)
  35. file_category = file_category(file_extension)
  36.  
  37. if not existing_file:
  38. # Store some file stats so we can compare duplicates later.
  39. file_stats.append({'root': root, 'name': name, 'size': size})
  40.  
  41. if not file_category:
  42. try:
  43. # Put the file at the base of the destination.
  44. os.rename(filepath, os.path.join(args.destination, name))
  45. except:
  46. print('Unable to move file %s' % (name))
  47.  
  48. else:
  49. try:
  50. # Put the file in the appropriate dir under the destination.
  51. os.rename(filepath, os.path.join(args.destination, file_category, name))
  52. except:
  53. print('Unable to move file %s' % (name))
  54.  
  55. else:
  56. if size != existing_file['size']:
  57.  
  58. if not file_category:
  59. try:
  60. # Put the file at the base of the destination.
  61. os.rename(filepath, os.path.join(args.destination, name))
  62. except:
  63. print('Unable to move file %s' % (name))
  64.  
  65. else:
  66. try:
  67. # Put the file in the appropriate dir under the destination.
  68. os.rename(filepath, os.path.join(args.destination, file_category, name))
  69. except:
  70. print('Unable to move file %s' % (name))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement