如何在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 - 表示將傳輸fsrc的檔案的類檔案物件,稱為fdst。

  • 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()方法允許您立即執行任何OS命令或指令碼。

命令或指令碼必須作為引數傳遞給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日

527 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告