ホームページ  >  記事  >  バックエンド開発  >  Python に基づいてファイル分類子を実装する方法

Python に基づいてファイル分類子を実装する方法

王林
王林転載
2023-06-03 16:46:031498ブラウズ

ソート対象のファイルディレクトリをカスタマイズすることで、ディレクトリ配下のすべてのファイルをファイル形式に応じて分類できます。

Python に基づいてファイル分類子を実装する方法

ロジックの実装に使用される Python テクノロジ スタックは、os、glob、shutil の 3 つの標準ライブラリを包括的に使用して、ファイルの自動並べ替えを完了します。

これら 3 つのファイル処理モジュールをそれぞれコード ブロックにインポートし、後続の開発操作を開始します。

# 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

注: フォルダー、特にシステム ディスクの移動によって発生する例外を回避するために、ここではコピー (shutil.copy 関数) が使用されます。

最後に、印刷機能を使用して、ファイル カテゴリの数と新しいフォルダーの数を印刷します。

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

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

プログラムの実行が完了した直後にコマンド ウィンドウが閉じられるのを避けるために、上記の input 関数を使用してウィンドウの一時停止の効果を維持します。

Python に基づいてファイル分類子を実装する方法

Python に基づいてファイル分類子を実装する方法

以上がPython に基づいてファイル分類子を実装する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。