首頁  >  文章  >  後端開發  >  基於Python怎麼實現文件分類器

基於Python怎麼實現文件分類器

王林
王林轉載
2023-06-03 16:46:031497瀏覽

透過自訂需要整理的檔案目錄,將該目錄下方的全部檔案依照檔案格式完成分類操作。

基於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

注意:為了避免移動資料夾而造成的異常,尤其是系統盤,因此這裡用的是複製,也就是shutil.copy函數使用。

最後,將檔案分類數量、資料夾新數量使用print函數進行列印即可。

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

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

為了避免程式執行完成後直接將命令視窗關閉,上面使用了input函數來保持視窗暫停的效果。

基於Python怎麼實現文件分類器

基於Python怎麼實現文件分類器

以上是基於Python怎麼實現文件分類器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除