📜  Python| shutil.move() 方法

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

Python| shutil.move() 方法

Python中的Shutil 模块提供了许多对文件和文件集合进行高级操作的功能。它属于 Python 的标准实用程序模块。该模块有助于自动化复制和删除文件和目录的过程。
shutil.move()方法 递归地将文件或目录(源)移动到另一个位置(目标)并返回目标。如果目标目录已经存在,则将 src 移动到该目录中。如果目标已经存在但不是目录,那么它可能会根据os.rename()语义被覆盖。

示例 #1:

使用shutil.move()方法将文件从源移动到目标

# Python program to explain shutil.move() 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 moving file:") 
print(os.listdir(path)) 
  
  
# Source path 
source = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/source'
  
# Destination path 
destination = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/destination'
  
# Move the content of 
# source to destination 
dest = shutil.move(source, destination) 
  
# List files and directories 
# in "C:/Users / Rajnish / Desktop / GeeksforGeeks" 
print("After moving file:") 
print(os.listdir(path)) 
  
# Print path of newly 
# created file 
print("Destination path:", dest) 
输出:
Before moving file:
['source']
After moving file:
['destination']
Destination path: C:/Users/Rajnish/Desktop/GeeksforGeeks/destination

示例 #2:
使用shutil.move() shutil.copytree()移动文件,并且目标目录已经存在。

# Python program to explain shutil.move() 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 moving file:") 
print(os.listdir(path)) 
  
  
# Source path 
source = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/source'
  
# Destination path 
destination = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/destination'
  
# Move the content of 
# source to destination
# using shutil.copytree() as parameter
dest = shutil.move(source, destination, copy_function = shutil.copytree) 
  
# List files and directories 
# in "C:/Users / Rajnish / Desktop / GeeksforGeeks" 
print("After moving file:") 
print(os.listdir(path)) 
  
# Print path of newly 
# created file 
print("Destination path:", dest) 
输出:
Before moving file:
['destination', 'source']
After moving file:
['destination']
Destination path: C:/Users/Rajnish/Desktop/GeeksforGeeks/destination\source