如何使用 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() 方法

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日

6K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.