如何使用 Python 將檔案從一個資料夾移動到另一個資料夾?


Python 的 shutil 模組提供了一些用於對單個檔案和檔案集合進行高階操作的函式。

我們可以將檔案從一個資料夾移動到另一個資料夾。你可以透過多種方式實現這一點。

使用 OS 模組

Python 的 OS 模組允許使用者與他們的作業系統進行互動。

shutil.move() 方法可以用來移動檔案。要將檔案從一個目錄移動到另一個目錄,請按照以下說明操作。

示例 - 使用 shutil.move() 方法

以下是如何使用 shutil.move() 方法將檔案從一個資料夾移動到另一個資料夾的示例:

# importing the modules import shutil import os # Providing the folder path origin = 'C:\Users\Lenovo\Downloads\Works\' target = 'C:\Users\Lenovo\Downloads\Work TP\' # Fetching the list of all the files files = os.listdir(origin) # Fetching all the files to directory for f in files: shutil.move(origin + f, target)

輸出

輸出結果顯示,“Works”資料夾中的檔案已移動到“Work TP”資料夾。

示例 - 使用 os.rename() 方法

os 模組的一個函式是 rename() 方法,用於將檔案從一個位置移動到另一個位置。此函式透過更改檔案的目錄名稱來移動檔案。

以下是如何使用 os.rename() 方法將檔案從一個資料夾移動到另一個資料夾的示例:

import os origin = 'C:\Users\Lenovo\Downloads\Works\' target = 'C:\Users\Lenovo\Downloads\Work TP\' files = os.listdir(origin) for q in files: os.rename(origin + q, target + q))

輸出

輸出結果顯示,“Works”資料夾中的檔案已移動到“Work TP”資料夾。

注意 - 可以使用 os.replace() 或 os.rename() 來更改檔案或目錄的名稱。根據你使用的作業系統,os.rename() 會以各種方式出現問題。

在開發需要與多個作業系統相容的軟體時,os.replace() 可能是一個更好的選擇,因為它會在各種系統上始終如一地報告錯誤。

使用 Pathlib 模組

Python 中一個常用的模組是 pathlib,它提供了一個用於管理各種檔案和字典的物件。Path 是用於處理檔案的主要物件。

示例

以下是如何使用 pathlib 模組將檔案從一個資料夾移動到另一個資料夾的示例:

from pathlib import Path import shutil import os origin = 'C:\Users\Lenovo\Downloads\Works\' target = 'C:\Users\Lenovo\Downloads\Work TP\' for f in Path(origin).glob('trial.py'): shutil.move(os.path.join(origin,f),target)

輸出

輸出結果顯示,“Works”資料夾中的檔案已移動到“Work TP”資料夾。

更新於:2022年8月18日

6000+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告