如何在 Python 中複製檔案?


在現代軟體開發中,以程式設計方式複製檔案是最常見的活動之一。在本教程中,我們將學習使用 shutil 模組在 Python 中傳輸檔案的幾種不同方法。

Shutil 是 Python 標準庫中的一個模組,它提供各種高階檔案操作。在檔案複製方面,該庫根據您是否要複製元資料或檔案許可權以及目標是否是目錄,提供了多種選項。它屬於 Python 基本實用程式模組的範疇。此模組有助於自動化檔案和目錄的複製和刪除。

shutil.copy

shutil.copy() 方法將指定原始檔(不包含元資料)複製到指定的目的地檔案或目錄,並返回新生成檔案的路徑。src 引數可以是字串或路徑型物件。

語法

以下是 shutil 庫中 copy 方法的語法。

Shutil.copy(source_file, destination_file)

示例 1

在這個示例中,我們將學習使用 shutil 庫將一個檔案複製到另一個檔案。

#program to copy a file using python
#importing the python library shutil
import shutil
#copying the file example.txt into example2.txt
shutil.copy('example.txt', 'example2.txt')
print("The file is copied")

輸出

以下程式碼的輸出如下所示。

The file is copied

shutil.copy2()

shutil.copy2()shutil.copy() 相同,區別在於 copy2() 還嘗試保留檔案元資料。

語法

以下是 shutil 庫中 shutil.copy2 方法的語法。

shutil.copy2(source, destination, *, follow_symlinks = True)

copy2 方法的引數:

  • source - 包含原始檔位置的字串。

  • destination - 包含檔案或目錄目標路徑的字串。

  • 如果 follow symlinks 傳遞 True - 此引數的預設值為 True。如果為 False 且 source 表示符號連結,則它嘗試將所有元資料從源符號連結複製到新生成的目的地符號連結。此功能是特定於平臺的。

  • 返回型別 - 此過程返回新生成檔案的路徑,作為字串。

示例 2

在這個示例中,我們將瞭解 shutil 庫中 copy2 方法的工作原理。

#program to copy a file using python
#importing the python library shutil
import shutil
#copying the file example.txt into example2.txt
shutil.copy2('example.txt', 'example2.txt')
print("The file is copied")

輸出

上述程式碼的輸出如下所示。

The file is copied

shutil.copyfileobj

如果您需要使用檔案物件,shutil.copyfileobj 是最佳選擇。該方法基本上將原始檔物件的內容複製到目標類檔案物件。您還可以選擇一個與用於傳輸資料的緩衝區大小匹配的長度。不會保留檔案許可權,並且目錄不能作為目標。不會複製元資料。

語法

以下是 shutil.copyfileobj 方法的語法。

shutil.copyfileobj(fsrc, fdst[, length])

shutil.copyfileobj 的引數如下:

  • Fsrc - 表示被複制原始檔的類檔案物件

  • Fdst - 一個稱為 fdst 的類檔案物件,表示將向其傳輸 fsrc 的檔案。

  • length - 一個可選的整數值,指示緩衝區的大小。

示例 3

在這裡,我們將瞭解如何在 shutil 庫中使用 copyfileobj 方法。如上所述,此方法用於將原始檔物件的內容複製到目標類檔案物件。

#program to copy a file using python
#importing the python library shutil
import shutil
#copying the file example.txt into example2.txt
source_file = open('example.txt', 'rb')
dest_file = open('example2.txt', 'wb')
shutil.copyfileobj(source_file, dest_file)
print("The file is copied")

輸出

上述程式碼的輸出顯示如下。

The file is copied

os.system() 方法

子 shell 中的 system() 方法允許您立即執行任何作業系統命令或指令碼。

命令或指令碼必須作為引數傳遞給 system() 函式。此方法在內部使用標準 C 庫函式。它的返回值是命令的退出狀態。

語法

os.system(command)

system() 方法的引數如下所示。

command - 它是字串型別,指示要執行的命令。

示例 4

在這個示例中,我們將看到如何使用 os.system() 方法複製檔案。如下所示。我們匯入所需的庫,然後使用 system 方法將命令“copy example.txt example2.txt”以字串的形式傳遞給 system 方法。

#program to copy a file using python
#importing the python library OS
import os
#copying example.txt into example2.txt
os.system('copy example.txt  example2.txt')

輸出

上述程式碼的輸出顯示如下。

sh: 1: copy: not found

更新於:2023年5月11日

529 次檢視

啟動您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.