Last active
August 29, 2015 14:18
-
-
Save bravikov/190df5f1249ebb9cb728 to your computer and use it in GitHub Desktop.
Скрипт сортирует файлы в папки по расширению
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' Рекурсивно получает список файлов в заданной папке. И копирует файлы в | |
другую заданную папку, сортируя их по расширению. | |
Для каждого расширения создается своя папка, имя которой совпадает с | |
расширением. Файлы без расширения помещаются в папку Прочее. | |
Если имена файлов с одним расширением повторяются, то для расширения создается | |
еще одна папка и к имени папки добавляется суффикс _N, где N равно 1, 2 и т. д. | |
Символьные ссылки игнорируются. | |
Если папки назначения не существует, то она будет создана. | |
Проверено работает с Python 3.4. ''' | |
dir1 = 'Источник' | |
dest_dir = 'Результат' | |
import os, shutil | |
# Возвращает список файлов в папке dir и всех подпапках. | |
def files(dir): | |
result = [] | |
try: | |
for name in os.listdir(dir): | |
path = os.path.join(dir, name) | |
if os.path.islink(path): | |
continue | |
if os.path.isfile(path): | |
result.append(path) | |
else: | |
result += files(path) | |
except FileNotFoundError: | |
pass | |
except PermissionError: | |
pass | |
except NotADirectoryError: | |
pass | |
return result | |
# Возвращает расширения файла. | |
def extension(file): | |
return os.path.splitext(file)[1][1:] | |
# Основной код | |
all_files = files(dir1) | |
file_count = len(all_files) | |
file_i = 0 | |
for src_file in all_files: | |
file_i += 1 | |
percent = round(file_i / file_count * 100, 2) | |
print(percent, '%', src_file) | |
ext = extension(src_file).lower() | |
if len(ext) == 0: | |
ext = 'Прочее' | |
basename = os.path.basename(src_file) | |
ext_dir = ext | |
full_dest_dir = '' | |
dest_file = '' | |
try_count = 1 | |
while True: | |
full_dest_dir = os.path.join(dest_dir, ext_dir) | |
dest_file = os.path.join(full_dest_dir, basename) | |
if not os.path.exists(dest_file): | |
break | |
try_count += 1 | |
ext_dir = ext + '_' + str(try_count) | |
if not os.path.exists(full_dest_dir): | |
try: | |
os.makedirs(full_dest_dir) | |
except OSError: | |
print('Не получилось создать каталог назначения.') | |
continue | |
try: | |
shutil.copyfile(src_file, dest_file) | |
except IOError: | |
print('Не получилось скопировать файл.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment