>  기사  >  백엔드 개발  >  Python 기반으로 파일 분류기를 구현하는 방법

Python 기반으로 파일 분류기를 구현하는 방법

王林
王林앞으로
2023-06-03 16:46:031496검색

정렬해야 하는 파일 디렉터리를 사용자 정의하면 해당 디렉터리 아래의 모든 파일을 파일 형식에 따라 분류할 수 있습니다.

Python 기반으로 파일 분류기를 구현하는 방법

로직을 구현하는 데 사용되는 Python 기술 스택은 자동화된 파일 구성을 완성하기 위해 os, glob 및 Shutil의 세 가지 표준 라이브러리를 포괄적으로 사용하는 것입니다.

이 세 가지 파일 처리 모듈을 각각 코드 블록으로 가져오고 후속 개발 작업을 시작하세요.

# It imports the os module.
import os

# Shutil is a module that provides a number of high-level operations on files and collections of files.
import shutil

# The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell,
# although results are returned in arbitrary order. No tilde expansion is done, but *, ?, and character ranges expressed
# with [] will be correctly matched.
import glob
import sys

분류가 필요한 파일 디렉터리의 uncatched_dir과 분류된 파일 저장 디렉터리의 target_dir을 수동으로 입력할 수 있도록 설정하세요.

# Asking the user to input the path of the directory that contains the files to be sorted.
uncatched_dir = input('请输入待分类的文件路径:\n')

# It checks if the uncatched_dir is empty.
if uncatched_dir.strip() == '':
    print('待分类的文件夹路径不能为空!')
    sys.exit()

# Asking the user to input the path of the directory that contains the files to be sorted.
target_dir = input('请输入分类后文件存放的目标路径:\n')

# It checks if the target_dir is empty.
if target_dir.strip() == '':
    print('分类后的文件存放路径不能为空!')
    sys.exit()

Python 기반으로 파일 분류기를 구현하는 방법

분류 후 입력한 파일 저장 디렉터리 경로가 새로운 경로로 입력될 가능성이 높으므로 존재하는지 확인하고, 없으면 새로운 경로를 생성하세요.

# It checks if the target_dir exists. If it does not exist, it creates a new directory in the current working directory.
if not os.path.exists(target_dir):
    # It creates a new directory in the current working directory.
    os.mkdir(target_dir)

파일 정렬 결과를 기록하기 위해 이동된 파일 수에 대해 file_move_num 변수를 정의하고 새로 생성된 폴더 수에 대해 dir_new_num 변수를 정의합니다.

# A variable that is used to count the number of files that have been moved.
file_move_num = 0

# A variable that is used to count the number of new directories that have been created.
dir_new_num = 0

정렬이 필요한 uncatched_dir 폴더 디렉터리를 탐색하고 해당 디렉터리 아래의 모든 유형의 파일을 자동으로 정렬합니다.

# A for loop that iterates through all the files in the uncatched_dir directory.
for file_ in glob.glob(f'{uncatched_dir}/**/*', recursive=True):

    # It checks if the file is a file.
    if os.path.isfile(file_):

        # It gets the file name of the file.
        file_name = os.path.basename(file_)

        # Checking if the file name contains a period.
        if '.' in file_name:

            # Getting the suffix of the file.
            suffix_name = file_name.split('.')[-1]

        else:

            # Used to classify files that do not have a suffix.
            suffix_name = 'others'

        # It checks if the directory exists. If it does not exist, it creates a new directory in the current working
        # directory.
        if not os.path.exists(f'{target_dir}/{suffix_name}'):

            # It creates a new directory in the current working directory.
            os.mkdir(f'{target_dir}/{suffix_name}')

            # Adding 1 to the variable dir_new_num.
            dir_new_num += 1

        # It copies the file to the target directory.
        shutil.copy(file_, f'{target_dir}/{suffix_name}')

        # Adding 1 to the variable file_move_num.
        file_move_num += 1

참고: 폴더, 특히 시스템 디스크 이동으로 인해 발생하는 예외를 방지하기 위해 여기서는 quitil.copy 기능인 복사본이 사용됩니다.

마지막으로 인쇄 기능을 사용하여 파일 카테고리 수와 새 폴더 수를 인쇄합니다.

print(f'整理完成,有{file_move_num}个文件分类到了{dir_new_num}个文件夹中!\n')

input('输入任意键关闭窗口...')

프로그램 실행이 완료된 후 명령창이 바로 닫히는 것을 방지하기 위해 위의 입력기능을 사용하여 창이 일시정지되는 효과를 유지하고 있습니다.

Python 기반으로 파일 분류기를 구현하는 방법

Python 기반으로 파일 분류기를 구현하는 방법

위 내용은 Python 기반으로 파일 분류기를 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제