📜  Python| shutil.copytree() 方法

📅  最后修改于: 2022-05-13 01:54:27.351000             🧑  作者: Mango

Python| shutil.copytree() 方法

Python中的Shutil 模块提供了许多对文件和文件集合进行高级操作的功能。它属于 Python 的标准实用程序模块。该模块有助于自动复制和删除文件和目录的过程。
shutil.copytree()方法递归地复制以源 (src) 为根的整个目录树到目标目录。由 (dst) 命名的目标目录必须不存在。它将在复制期间创建。使用 copystat() 复制目录的权限和时间,使用 shutil.copy2() 复制单个文件。

示例 #1:
使用shutil.copytree()方法将文件从源复制到目标

# Python program to explain shutil.copytree() method 
       
# importing os module 
import os 
   
# importing shutil module 
import shutil 
   
# path 
path = 'C:/Users / Rajnish / Desktop / GeeksforGeeks'
   
# List files and directories 
# in 'C:/Users / Rajnish / Desktop / GeeksforGeeks' 
print("Before copying file:") 
print(os.listdir(path)) 
   
   
# Source path 
src = 'C:/Users / Rajnish / Desktop / GeeksforGeeks / source'
   
# Destination path 
dest = 'C:/Users / Rajnish / Desktop / GeeksforGeeks / destination'
   
# Copy the content of 
# source to destination 
destination = shutil.copytree(src, dest) 
   
# List files and directories 
# in "C:/Users / Rajnish / Desktop / GeeksforGeeks" 
print("After copying file:") 
print(os.listdir(path)) 
   
# Print path of newly 
# created file 
print("Destination path:", destination)
输出:
Before copying file:
['source']
After copying file:
['destination', 'source']
Destination path: C:/Users/Rajnish/Desktop/GeeksforGeeks/destination

示例 #2:
使用shutil.copytree()方法通过shutil.copy() () 方法复制文件。

# Python program to explain shutil.copytree() method 
        
# importing os module 
import os 
    
# importing shutil module 
import shutil 
    
# path 
path = 'C:/Users / Rajnish / Desktop / GeeksforGeeks'
    
# List files and directories 
# in 'C:/Users / Rajnish / Desktop / GeeksforGeeks' 
print("Before copying file:") 
print(os.listdir(path)) 
    
    
# Source path 
src = 'C:/Users / Rajnish / Desktop / GeeksforGeeks / source'
    
# Destination path 
dest = 'C:/Users / Rajnish / Desktop / GeeksforGeeks / destination'
    
# Copy the content of 
# source to destination 
# using shutil.copy() as parameter
destination = shutil.copytree(src, dest, copy_function = shutil.copy) 
    
# List files and directories 
# in "C:/Users / Rajnish / Desktop / GeeksforGeeks" 
print("After copying file:") 
print(os.listdir(path)) 
    
# Print path of newly 
# created file 
print("Destination path:", destination)
输出:
Before copying file:
['source']
After copying file:
['destination', 'source']
Destination path: C:/Users/Rajnish/Desktop/GeeksforGeeks/destination