當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python shutil.copy2()用法及代碼示例


Python中的Shutil模塊提供了許多對文件和文件集合進行高級操作的函數。它屬於Python的標準實用程序模塊。此模塊有助於自動執行文件和目錄的複製和刪除過程。

shutil.copy2()Python中的方法用於將源文件的內容複製到目標文件或目錄。此方法與shutil.copy()方法,但它還會嘗試保留文件的元數據。

源必須代表文件,但目標可以是文件或目錄。如果目標是目錄,則文件將使用源中的基本文件名複製到目標中。另外,目的地必須是可寫的。如果目標是文件並且已經存在,則將其替換為源文件,否則將創建一個新文件。


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

參數:
source:代表源文件路徑的字符串。
destination:代表目標文件或目錄路徑的字符串。
follow_symlinks(可選):此參數的默認值為True。如果為False,並且source表示符號鏈接,則它將嘗試將所有元數據從源符號鏈接複製到newly-created目標符號鏈接。此函數取決於平台。

Note:參數列表中的“ *”表示以下所有參數(此處為“ follow_symlinks”)僅是關鍵字參數,可以使用其名稱(而不是位置參數)來提供。

返回類型:此方法返回一個表示新創建文件路徑的字符串。

代碼1:使用shutil.copy2()方法將文件從源複製到目標
# Python program to explain shutil.copy2() method  
    
# importing os module  
import os 
  
# importing shutil module  
import shutil 
  
# path 
path = '/home/User/Documents'
  
# List files and directories 
# in '/home/User/Documents' 
print("Before copying file:") 
print(os.listdir(path)) 
  
  
# Source path 
source = "/home/User/Documents/file.txt"
  
# Print the metadeta 
# of source file 
metadata = os.stat(source) 
print("Metadata:", metadata, "\n") 
  
# Destination path 
destination = "/home/User/Documents/file(copy).txt"
  
# Copy the content of 
# source to destination 
dest = shutil.copy2(source, destination) 
  
# List files and directories 
# in "/home / User / Documents" 
print("After copying file:") 
print(os.listdir(path)) 
  
# Print the metadata 
# of the destination file 
matadata = os.stat(destination) 
print("Metadata:", metadata) 
  
# Print path of newly  
# created file 
print("Destination path:", dest)
輸出:
Before copying file:
['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'copy.cpp']
Metadata:  os.stat_result(st_mode=33188, st_ino=801113, st_dev=2056, st_nlink=1,
st_uid=1000, st_gid=1000, st_size=84, st_atime=1558866178, st_mtime=1558866156, 
st_ctime=1558866156) 

After copying file:
['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'file(copy).txt', 'copy.cpp']
Metadata: os.stat_result(st_mode=33188, st_ino=801111, st_dev=2056, st_nlink=1,
st_uid=1000, st_gid=1000, st_size=84, st_atime=1558866178, st_mtime=1558866156,
st_ctime=1558933947)
Destination path: /home/User/Documents/file(copy).txt
代碼2:如果目的地是目錄
# Python program to explain shutil.copy2() method  
    
# importing os module  
import os 
  
# importing shutil module  
import shutil 
  
  
# Source path 
source = "/home/User/Documents/file.txt"
  
# Destination path 
destination = "/home/User/Desktop/"
  
# Copy the content of 
# source to destination 
dest = shutil.copy2(source, destination) 
  
# List files and directories 
# in "/home / User / Desktop" 
print("After copying file:") 
print(os.listdir(destination)) 
  
# Print path of newly  
# created file 
print("Destination path:", dest)
輸出:
After copying file:
['input.txt', 'GeeksForGeeks', 'output.txt', 'file.txt', 'web.py', 'tree.cpp']
Destination path: /home/User/Desktop/file.txt
代碼3:使用shutil.copy2()方法時可能出現的錯誤
# Python program to explain shutil.copy2() method  
    
# importing shutil module  
import shutil 
  
  
# If the source and destination 
# represents the same file 
# 'SameFileError' exception 
# will be raised 
  
# If the destination is 
# not writable 
# 'PermissionError' exception 
# will be raised 
  
  
# Source path 
source = "/home/User/Documents/file.txt"
  
# Destination path 
destination = "/home/User/Documents/file.txt"
  
# Copy the content of 
# source to destination 
shutil.copy2(source, destintion)
輸出:
Traceback (most recent call last):
  File "try.py", line 26, in 
    dest = shutil.copy(source, destination)
  File "/usr/lib/python3.6/shutil.py", line 241, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "/usr/lib/python3.6/shutil.py", line 104, in copyfile
    raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
shutil.SameFileError: '/home/User/Desktop/file.txt' and  '/home/User/Desktop/file.txt'
are the same file
代碼4:使用shutil.copy2()方法處理錯誤
# Python program to explain shutil.copy2() method  
    
# importing shutil module  
import shutil 
  
# Source path 
source = "/home/User/Documents/file.txt"
  
# Destination path 
destination = "/home/User/Documents/file.txt"
  
# Copy the content of 
# source to destination 
  
try: 
    shutil.copy2(source, destination) 
    print("File copied successfully.") 
  
# If source and destination are same 
except shutil.SameFileError: 
    print("Source and destination represents the same file.") 
  
# If there is any permission issue 
except PermissionError: 
    print("Permission denied.") 
  
# For other errors 
except: 
    print("Error occurred while copying file.")
輸出:
Source and destination represents the same file.

參考: https://docs.python.org/3/library/shutil.html



相關用法


注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | shutil.copy2() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。