Python| shutil.move() 方法
Python中的Shutil 模块提供了许多对文件和文件集合进行高级操作的功能。它属于 Python 的标准实用程序模块。该模块有助于自动化复制和删除文件和目录的过程。
shutil.move()
方法 递归地将文件或目录(源)移动到另一个位置(目标)并返回目标。如果目标目录已经存在,则将 src 移动到该目录中。如果目标已经存在但不是目录,那么它可能会根据os.rename()
语义被覆盖。
Syntax: shutil.move(source, destination, copy_function = copy2)
Parameters:
source: A string representing the path of the source file.
destination: A string representing the path of the destination directory.
copy_function (optional): The default value of this parameter is copy2. We can use other copy function like copy, copytree, etc for this parameter.
Return Value: This method returns a string which represents the path of newly created file.
示例 #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
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。