使用 Python 將檔案移動到以建立和修改日期命名的目錄
在本問題陳述中,我們必須藉助 Python 將資料夾中的所有檔案移動到以建立和修改日期命名的目錄中。在此任務中,我們將使用 Python 的一些預定義庫來平滑地處理檔案重新定位。
理解問題
正如我們所見,根據日期或修改和建立時間來管理檔案。因此,在本文中,我們將透過建立 Python 指令碼簡化此任務,該指令碼將根據建立和修改日期移動檔案,並將資料夾名稱作為修改或建立日期。因此,基本上我們將查詢該資料夾並移動檔案,如果不存在根據日期命名的資料夾,我們將建立一個新資料夾,並根據檔案的修改日期命名它,並將這些檔案按建立或修改日期排序移動。

在上圖中,我們可以看到這些檔案及其修改日期。因此,我們將這些檔案移動到修改日期資料夾中以對其進行整理。
演算法
步驟 1 − 首先在 Python 指令碼的開頭匯入必要的庫。在我們的程式中,我們正在匯入 OS、shutil 和 datetime 庫。
步驟 2 − 定義存在檔案的原始檔路徑以執行移動操作。
步驟 3 − 然後將當前工作目錄更改為源目錄。然後列出當前目錄中的所有目錄和檔案。
步驟 4 − 因此,我們將需要一個工作資料夾,因此我們將使用 os 庫的 getcwd 函式。
步驟 5 − 現在我們將使用 for 迴圈遍歷當前工作目錄中的所有檔案。
步驟 6 − 在迴圈內部,我們將當前目錄路徑與檔案或目錄名稱連線起來。
步驟 7 − 檢查條件,如果我們處於正確的路徑上,則將所有檔案移動到當前目錄。並在檔案移動後刪除目錄。
步驟 8 − 如果未找到正確的路徑,則獲取檔案的修改日期並建立目錄,並將其命名為修改日期。並將所有檔案移動到目標資料夾。
示例
import os as system import shutil import datetime source_directory = r"F:/Python Tutorial/Tutorialspoint folder/test" # Change the current working directory to the source directory system.chdir(source_directory) # List all directories and files in the current directory all_files = system.listdir() # need the current working folder output = system.getcwd() # Loop over each file in the current folder for dir_or_file in all_files: try: # Join the current directory path with the file/directory name path = system.path.join(output, dir_or_file) if system.path.isdir(path): # move directory's files to the current directory dir_files = system.listdir(path) for dir_file in dir_files: file_path = system.path.join(path, dir_file) shutil.move(file_path, output) # When the files are moved so remove the directory shutil.rmtree(path) else: # Get file's modification date modify_time = system.path.getmtime(path) modify_date = datetime.datetime.fromtimestamp(modify_time) # Create the directory as per the modification date dir_name = modify_date.strftime("%b-%d-%Y") dest = system.path.join(output, dir_name) # If directory is not present the Create it system.makedirs(dest, exist_ok=True) # Move the file to the destination folder shutil.move(path, dest) except Exception as e: print(f"Error occurred: {e}") print("Successfully moved the files.")
輸出
$$\mathrm{移動前}$$

$$\mathrm{移動後}$$


結論
因此,我們建立了一個程式碼,可以使用 Python 將所有檔案移動到以建立和修改日期命名的目錄中。因此,基本上我們使用了 Python 的 os、shutil 和 datetime 庫。我們遍歷了源路徑中的所有檔案和目錄,並將欄位移動到相應的目錄。