如何使用 Python 將檔案複製到新目錄?


將檔案複製到新目錄是每個 Python 開發人員都必須具備的基本技能。無論是在備份資料、組織檔案還是建立新專案的過程中,Python 都提供了強大的工具,使檔案複製變得輕而易舉。在本篇詳盡的文章中,您將學習如何使用 Python 將檔案複製到新目錄。詳細的解釋和實用的程式碼示例將幫助您獲得知識和信心,成功處理檔案複製任務。

瞭解檔案複製

在開始本文中的示例之前,讓我們花點時間瞭解檔案複製的概念。檔案複製是指複製一個檔案的內容並將其儲存到或傳輸到不同的位置。此過程使我們能夠進行備份、在目錄之間移動檔案,甚至建立同一檔案的多個版本。

複製單個檔案

讓我們考慮一個簡單的程式碼示例,其中我們將學習如何在 Python 中將單個檔案複製到新目錄。

示例

在此示例中,匯入了 shutil 模組;它為高階檔案操作提供了功能。我們將要複製的檔案的路徑分配給 source_file 變數。接下來,我們宣告 destination_directory 變數,它指示我們要將複製的檔案儲存在哪個目錄中。最後,使用 shutil.copy() 函式執行檔案複製操作。

import shutil

# Specify the source file path
source_file = '/path/to/your/source/file.txt'

# Specify the destination directory path
destination_directory = '/path/to/your/destination/directory/'

# Copy the file to the destination directory
shutil.copy(source_file, destination_directory)

複製多個檔案

通常,我們可能希望一次將多個檔案複製到新目錄。以下程式碼示例演示瞭如何在 Python 中實現此目的。

示例

在此程式碼示例中,我們一起匯入了 glob 模組和 shutil 模組。我們宣告 source_directory 變數以顯示包含我們希望複製或重複的檔案的目錄的路徑。類似地,我們將 destination_directory 變數宣告為我們希望將複製的檔案儲存在其中的目標目錄。透過使用 glob.glob() 函式和模式 source_directory + '/*',我們獲取源目錄中所有檔案的列表。然後,我們遍歷每個檔案並將其複製到目標目錄,使用 shutil.copy()。

import shutil
import glob
# Specify the source directory path
source_directory = '/path/to/your/source/directory/'

# Specify the destination directory path
destination_directory = '/path/to/your/destination/directory/'
# Get a list of all files in the source directory

files = glob.glob(source_directory + '/*')

# Copy each file to the destination directory
for file in files:
   shutil.copy(file, destination_directory)

重新命名複製檔案

在某些情況下,我們可能希望在重新命名檔案後將檔案複製到新目錄。下面給出的程式碼示例演示瞭如何在 Python 中完成此任務。

示例

在此程式碼中,我們將 source_file 變數分配給要複製的檔案的路徑。然後,我們宣告 destination_file 變數,其中包含複製檔案的路徑和新的所需名稱,該檔案將被重新命名。

透過利用 shutil.copy() 函式並提供目標檔案路徑,我們將檔案複製到新目錄,同時相應地重新命名它。

import shutil

# Specify the source file path
source_file = '/path/to/your/source/file.txt'

# Specify the destination file path with the desired name
destination_file = '/path/to/your/destination/new_file.txt'

# Copy the file to the destination directory with renaming
shutil.copy(source_file, destination_file)

輸出

對於某些特定的原始檔,輸出可能是

/content/sample_data/newactive_config

處理錯誤和異常

在檔案複製操作期間,處理可能發生的錯誤和異常至關重要。以下示例演示瞭如何在複製檔案時整合錯誤處理。

示例

在這裡,在此程式碼段中,我們使用 try-except 塊來處理檔案複製過程中可能發生的異常。我們嘗試在 try 塊中使用 shutil.copy() 複製檔案。如果發生 FileNotFoundError,則表示原始檔不存在。如果發生 IsADirectoryError,則表示目標路徑指向目錄而不是檔案。如果許可權不足以複製檔案,則可能會發生 PermissionError。最後,except Exception 塊充當萬能捕獲,用於處理可能發生的任何其他不可預見的錯誤。透過合併和整合錯誤處理,我們可以在檔案複製期間巧妙地處理各種情況。

import shutil

# Specify the source file path
source_file = '/path/to/your/source/file.txt'

# Specify the destination directory path
destination_directory = '/path/to/your/destination/directory/'

try:
   # Copy the file to the destination directory
   shutil.copy(source_file, destination_directory)
   print("File copied successfully!")
except FileNotFoundError:
   print("Source file not found.")
except IsADirectoryError:
   print("Destination is a directory.")
except PermissionError:
   print("Permission denied.")
except Exception as e:
   print("An error occurred:", str(e))

輸出

對於某些特定的原始檔,輸出可能是

File copied successfully!

在本篇全面而詳盡的文章中,我們介紹並探討了使用 Python 將檔案複製到新目錄的過程。我們考慮了複製單個檔案、複製多個檔案、以及重新命名複製檔案和處理可能出現的錯誤和異常的程式碼示例。有了這些策略作為您的資源,您現在可以在 Python 專案中自信地管理檔案複製任務。請記住考慮原始檔路徑、目標目錄以及任何特定要求,例如重新命名檔案。透過像專家一樣在 Python 中進行檔案複製,您可以輕鬆有效地組織、備份和操作檔案,從而實現您的編碼能力。

更新於: 2023-07-17

6K+ 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告