Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2020
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. import os
  2. import re
  3. from shutil import copyfile
  4.  
  5.  
  6. reg_book_id = re.compile('book-(.+)\)')
  7. sorted_dir = os.path.join(os.getcwd(), 'sorted')
  8. books_without_ids_dir = os.path.join(sorted_dir, 'books')
  9.  
  10. def prettify_name(filename):
  11.     _, file_extension = os.path.splitext(filename)
  12.     name = filename.split('_')[0]
  13.     pretty_name = ' '.join([word.capitalize() for word in name.split('-')])
  14.     return f'{pretty_name}{file_extension}'
  15.  
  16. print('Current dir: ', os.getcwd())
  17. for filename in os.listdir('.'):
  18.     if filename == '.' or filename == '..' or filename == __file__:
  19.         continue
  20.    
  21.     match = reg_book_id.search(filename)
  22.     pretty_filename = prettify_name(filename)
  23.     source = os.path.join(os.getcwd(), filename)
  24.  
  25.     try:
  26.         book_id = match.groups()[0]
  27.     except AttributeError:
  28.         print('Could not extract book id from: ' + filename)
  29.         if not os.path.exists(books_without_ids_dir):
  30.             print('Creating ' + books_without_ids_dir)
  31.             os.makedirs(books_without_ids_dir)
  32.        
  33.         destination = os.path.join(books_without_ids_dir, pretty_filename)
  34.         print(f'src: {source}\ndst: {destination}\n\n')
  35.         copyfile(source, destination)
  36.         continue
  37.  
  38.     book_dir = os.path.join(sorted_dir, book_id)
  39.     if not os.path.exists(book_dir):
  40.         os.makedirs(book_dir)
  41.        
  42.     destination = os.path.join(book_dir, pretty_filename)
  43.     print(f'src: {source}\ndst: {destination}\n\n')
  44.     copyfile(source, destination)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement