如何在Python中移动文件和目录
Python提供了将文件或目录从一个位置移动到另一个位置的功能。这可以使用shutil模块中的shutil.move()
函数来实现。 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 functions like copy, copytree, etc for this parameter.
Return Value: This method returns a string that represents the path of a newly created file.
内部测试:
A内:
我们想将目录 B 移动到目录 A。下面是实现。
# Python program to move
# files and directories
import shutil
# Source path
source = "D:\Pycharm projects\gfg\Test\B"
# Destination path
destination = "D:\Pycharm projects\gfg\Test\A"
# Move the content of
# source to destination
dest = shutil.move(source, destination)
# print(dest) prints the
# Destination of moved directory
输出:
内部测试:
A内:
示例#2:现在假设我们要使用shutil.copytree()
将上述目录 A 的所有子目录和文件移动到目录 G 并且目标目录不存在。下面是实现。
# Python program to move
# files and directories
import shutil
# Source path
source = "D:\Pycharm projects\gfg\Test\A"
# Destination path
destination = "D:\Pycharm projects\gfg\Test\G"
# Move the content of
# source to destination
dest = shutil.move(source, destination, copy_function = shutil.copytree)
# print(dest) prints the
# Destination of moved directory
输出:
内部测试:
G内: