Рубрики
Без рубрики

Автоматизируйте скучные файлы, организующие с помощью Python (Организатор Python Files)

вступление Здравствуйте сегодня, мы собираемся кодировать организатор файлов, используя скрипт Python, он будет … Tagged с помощью Python, программирования, файлов.

вступление

Здравствуйте сегодня, мы собираемся кодировать органайзер файлов, используя скрипт Python, он будет организовать файлы по их типам, например, он будет размещать все файлы с расширением (.png) в папку с именем, с именем Pictures Let’s Code … (Этот пост опубликован здесь Организатор Python Files, автоматизируйте скучные файлы, организующие с помощью Python )

Кодирование

Импорт необходимых модулей

это те модули, которые мы собираемся использовать

Если у вас есть какие -либо проблемы, вы можете опубликовать ее в комментариях

import os
import pathlib
import shutil
import fnmatch

Подготовка папки по умолчанию для каждого типа файлов

Итак, теперь мы собираемся установить папку для каждого типа, например, мы хотим перенести картинки в папку в пути ‘/home/rin/downloads/’

В моем случае я использую Linux в Windows, пути будут выглядеть как ‘c: \ rin \ brink \ pictures’

## define path for every category
file_folder={
    'Music':'/home/rin/Downloads/',
    'Pictures':'/home/rin/Pictures/',
    'Documents':'/home/rin/Documents/',
    'Archives':'/home/rin/Archives/',
    'Videos':'/home/rin/Videos/',
    'Codes':'/home/rin/Codes/'
}

Определение типа файла с помощью расширения

Что такое расширение?

A Расширение файла или Имя файла расширение является окончанием файла, который помогает определить тип файла в операционных системах, таких как Microsoft Windows. В Microsoft Windows расширение имени файла является периодом, за которым часто следует три символа, но также может быть один, два или четыре символа.

В качестве примера, имя файла «myfile.txt» имеет расширение файла «.txt», которое представляет собой расширение имени файла, связанное с текстовыми файлами.

Итак, код:

## define the type of every extension
file_type={'Pictures':['.jpg', '.jpeg', '.jpe','.png','.jp2','.ico', '.wbmp','.j2k', '.jpf', '.jpx', '.jpm', '.mj2','.svg', '.svgz','.webp','.gif']
,'Music':['mp3']
,'Videos':['.mp4','.srt','.mkv','.3gp','.m4a']
,'Documents':['.pdf','.docx','.doc','.csv','.txt','.xls','.xlsx','.log']
,'Archives':['.zip','.tar']
,'Codes':['.py']}

Главный код

Теперь мы проходим путь к папке содержит нужные файлы, которые мы хотим, чтобы организовать в качестве примера для меня, я хочу чисто моя папка для загрузки

path='/home/rin/Downloads/'

Итак, теперь мы хотим сделать все файлы в папке и проверить тип каждого файла, затем переместите его в папку, содержит его тип

files=os.listdir(path)# list of files in the folder
for file in files:#for for every file in the list
    extension=pathlib.Path(file).suffix #extension of file ex:(.txt)
    #Documents
    if extension in file_type['Documents']:#check if the file is a document
        move=pathlib.Path(path+file).rename(file_folder['Documents']+file)# move the file to the folder conatins documents
        #move=shutil.move(path+file,file_folder['Documents'])
        print('success #### {} to {}'.format(file,move))
    #Music    
    if extension in file_type['Music']:
        move=pathlib.Path(path+file).rename(file_folder['Music']+file)
        #move=shutil.move(path+file,file_folder['Music'])
        print('success #### {} to {}'.format(file,move))
    #Pictures
    if extension in file_type['Pictures']:
        move=pathlib.Path(path+file).rename(file_folder['Pictures']+file)
        #move=shutil.move(path+file,file_folder['Pictures'])
        print('success #### {} to {}'.format(file,move))
    #Videos
    if extension in file_type['Videos']:
        move=pathlib.Path(path+file).rename(file_folder['Videos']+file)
        #move=shutil.move(path+file,file_folder['Videos'])
        print('success #### {} to {}'.format(file,move))
    #Archives
    if extension in file_type['Archives']:
        move=pathlib.Path(path+file).rename(file_folder['Archives']+file)
        #move=shutil.move(path+file,file_folder['Archives'])
        print('success #### {} to {}'.format(file,move))
    #Codes
    if extension in file_type['Codes']:
        move=pathlib.Path(path+file).rename(file_folder['Codes']+file)
        #move=shutil.move(path+file,file_folder['Codes'])
        print('success #### {} to {}'.format(file,move))
    else:
        print('## '+file)

Примечание: вы можете добавить больше типов

Полный исходный код

Не забудьте изменить пути Также вы можете добавить больше категории быть умным ..

import os
import pathlib
import shutil
import fnmatch
## define path for every category
file_folder={
    'Music':'/home/rin/Downloads/',
    'Pictures':'/home/rin/Pictures/',
    'Documents':'/home/rin/Documents/',
    'Archives':'/home/rin/Archives/',
    'Videos':'/home/rin/Videos/',
    'Codes':'/home/rin/Codes/'
}
## define the type of every extension
file_type={'Pictures':['.jpg', '.jpeg', '.jpe','.png','.jp2','.ico', '.wbmp','.j2k', '.jpf', '.jpx', '.jpm', '.mj2','.svg', '.svgz','.webp','.gif']
,'Music':['mp3']
,'Videos':['.mp4','.srt','.mkv','.3gp','.m4a']
,'Documents':['.pdf','.docx','.doc','.csv','.txt','.xls','.xlsx','.log']
,'Archives':['.zip','.tar']
,'Codes':['.py']}

path='/home/rin/Downloads/'
files=os.listdir(path)# list of files in the folder
for file in files:#for for every file in the list
    extension=pathlib.Path(file).suffix #extension of file ex:(.txt)
    #Documents
    if extension in file_type['Documents']:#check if the file is a document
        move=pathlib.Path(path+file).rename(file_folder['Documents']+file)# move the file to the folder conatins documents
        #move=shutil.move(path+file,file_folder['Documents'])
        print('success #### {} to {}'.format(file,move))
    #Music    
    if extension in file_type['Music']:
        move=pathlib.Path(path+file).rename(file_folder['Music']+file)
        #move=shutil.move(path+file,file_folder['Music'])
        print('success #### {} to {}'.format(file,move))
    #Pictures
    if extension in file_type['Pictures']:
        move=pathlib.Path(path+file).rename(file_folder['Pictures']+file)
        #move=shutil.move(path+file,file_folder['Pictures'])
        print('success #### {} to {}'.format(file,move))
    #Videos
    if extension in file_type['Videos']:
        move=pathlib.Path(path+file).rename(file_folder['Videos']+file)
        #move=shutil.move(path+file,file_folder['Videos'])
        print('success #### {} to {}'.format(file,move))
    #Archives
    if extension in file_type['Archives']:
        move=pathlib.Path(path+file).rename(file_folder['Archives']+file)
        #move=shutil.move(path+file,file_folder['Archives'])
        print('success #### {} to {}'.format(file,move))
    #Codes
    if extension in file_type['Codes']:
        move=pathlib.Path(path+file).rename(file_folder['Codes']+file)
        #move=shutil.move(path+file,file_folder['Codes'])
        print('success #### {} to {}'.format(file,move))
    else:
        print('## '+file)

Не стесняйтесь разрабатывать код и разместить любую проблему или запрос в комментариях

Оригинал: “https://dev.to/xbudy/automate-boring-files-organizing-using-python-python-files-organizer-21f4”