organize.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import os
  2. import shutil
  3. try:
  4. import logger
  5. except ImportError:
  6. from . import logger
  7. def organize_videos():
  8. # Make a variable equal to the names of the files in the current directory.
  9. current_dir_files = os.listdir()
  10. # The downloaded livestream(s) are in MP4 format.
  11. video_format = ['mp4']
  12. # Find the MP4 files and save them in a variable called 'filenames'.
  13. filenames = [filename for filename in current_dir_files
  14. if filename.split('.')[-1] in video_format]
  15. if len(filenames) == 0:
  16. logger.error("No MP4 files in the current directory.")
  17. return
  18. # We want a dictionary where the filenames are the keys
  19. # and the usernames are the values.
  20. filenames_to_usernames = {}
  21. # Populate the dictionary by going through each filename and removing the
  22. # undesired characters, leaving just the usernames.
  23. for filename in filenames:
  24. filename_parts = filename.split('_')[1:-3]
  25. usernames = '_'.join(filename_parts)
  26. filenames_to_usernames[filename] = usernames
  27. # The usernames are the values of the filenames_to_usernames dictionary.
  28. usernames = set(filenames_to_usernames.values())
  29. # Make a folder for each username.
  30. for username in usernames:
  31. if not os.path.isdir(username):
  32. os.mkdir(username)
  33. # Move the videos into the folders
  34. for filename, username in filenames_to_usernames.items():
  35. shutil.move(filename, username)
  36. num_videos_moved = len(filenames_to_usernames.keys())
  37. logger.info("{} videos moved successfully.".format(num_videos_moved))