使用Python递归复制目录(附示例)
Python中的Shutil 模块提供了许多对文件和文件集合进行高级操作的功能。它属于 Python 的标准实用程序模块。该模块有助于自动复制和删除文件和目录的过程。
shutil.copytree() 方法递归地复制以源 (src) 为根的整个目录树到目标目录。由 (dst) 命名的目标目录必须不存在。它将在复制期间创建。使用 copystat() 复制目录的权限和时间,使用 shutil.copy2() 复制单个文件。
Syntax: shutil.copytree(src, dst, symlinks = False, ignore = None, copy_function = copy2, ignore_dangling_symlinks = False)
Parameters:
src: A string representing the path of the source directory.
dest: A string representing the path of the destination.
symlinks (optional): This parameter accepts True or False, depending on which the metadata of the original links or linked links will be copied to the new tree.
ignore (optional): If ignore is given, it must be a callable that will receive as its arguments the directory being visited by copytree(), and a list of its contents, as returned by os.listdir().
copy_function (optional): The default value of this parameter is copy2. We can use other copy function like copy() for this parameter.
ignore_dangling_symlinks (optional): This parameter value when set to True is used to put a silence on the exception raised if the file pointed by the symlink doesn’t exist.
Return Value: This method returns a string which represents the path of newly created directory.
示例:假设目录如下所示。
我们想将文件夹“src”复制到一个新文件夹“dst”。下面是实现。
Python3
# Python program to explain shutil.copytree() method
# importing shutil module
import shutil
# path
path = 'D:/Pycharm projects/GeeksforGeeks/'
# Source path
src = 'D:/Pycharm projects/GeeksforGeeks/src'
# Destination path
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
# Copy the content of
# source to destination
destination = shutil.copytree(src, dest)
# print(destination) prints the
# path of newly created file
Python3
# Python program to demonstrate
# shutil.copytree()
# Importing module
import shutil
import errno
# Source path
src = 'D:/Pycharm projects/GeeksforGeeks/src/b/test_b.txt'
# Destination path
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
# Copy the content of
# source to destination
try:
shutil.copytree(src, dest)
except OSError as err:
# error caused if the source was not a directory
if err.errno == errno.ENOTDIR:
shutil.copy2(src, dest)
else:
print("Error: % s" % err)
Python3
# Python program to demonstrate
# shutil.copytree()
# importing modules
import shutil
# Declaring the ignore function
def ignoreFunc(file):
def _ignore_(path, names):
# List containing names of file
# that are needed to ignore
ignored = []
# check if file in names
# then add it to list
if file in names:
ignored.append(file)
return set(ignored)
return _ignore_
# Source path
src = 'D:/Pycharm projects /GeeksforGeeks/src'
# Destination path
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
# Copying the contents from Source
# to Destination without some
# specified files or directories
shutil.copytree(src, dest, ignore = ignoreFunc('a'))
Python3
# Python program to demonstrate
# shutil.copytree()
# importing modules
import shutil
# Source path
src = 'D:/Pycharm projects/GeeksforGeeks/src'
# Destination path
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
# Copying the contents from Source
# to Destination without some
# specified files or directories
shutil.copytree(src, dest, ignore = shutil.ignore_patterns('*.txt', 'a'))
输出:
复制文件和目录
稍微调整一下上面的代码,我们就可以复制文件或目录。这可以使用 copytree()函数和 try-except 块来完成。我们将捕获异常,如果异常是 ENOTDIR,那么我们将使用 copy2()函数来复制文件。这样做允许我们使用单个代码复制文件和目录。
假设目标目录如下所示。
我们想将 src 文件夹中的文本文件复制到这个目标文件夹。下面是实现。
Python3
# Python program to demonstrate
# shutil.copytree()
# Importing module
import shutil
import errno
# Source path
src = 'D:/Pycharm projects/GeeksforGeeks/src/b/test_b.txt'
# Destination path
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
# Copy the content of
# source to destination
try:
shutil.copytree(src, dest)
except OSError as err:
# error caused if the source was not a directory
if err.errno == errno.ENOTDIR:
shutil.copy2(src, dest)
else:
print("Error: % s" % err)
输出:
忽略文件和目录
有时,在将目录复制到另一个目录时,可能不想复制某些文件或子目录。甚至这也是由 shutil 模块处理的。函数copytree() 接受参数 ignore 允许指定一个返回应该被忽略的目录或文件列表的函数。此函数将文件或目录名称作为参数,用作名称过滤器。如果传递的参数在名称中,则将其添加到指定要跳过哪个文件或目录的 copytree() 的列表中。
示例:假设源文件夹如下所示。
我们想用文件夹'a'复制上面文件夹的内容。下面是实现。
Python3
# Python program to demonstrate
# shutil.copytree()
# importing modules
import shutil
# Declaring the ignore function
def ignoreFunc(file):
def _ignore_(path, names):
# List containing names of file
# that are needed to ignore
ignored = []
# check if file in names
# then add it to list
if file in names:
ignored.append(file)
return set(ignored)
return _ignore_
# Source path
src = 'D:/Pycharm projects /GeeksforGeeks/src'
# Destination path
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
# Copying the contents from Source
# to Destination without some
# specified files or directories
shutil.copytree(src, dest, ignore = ignoreFunc('a'))
输出:
要删除多个文件或具有特定格式的文件,使用 shutil.ignore_patterns。此函数作为参数传递给 copytree() 方法,该方法指定 glob 模式以过滤掉文件和目录。
示例:我们将使用上面的源文件夹作为示例,不会复制任何 .txt 文件和文件夹“a”。下面是实现。
Python3
# Python program to demonstrate
# shutil.copytree()
# importing modules
import shutil
# Source path
src = 'D:/Pycharm projects/GeeksforGeeks/src'
# Destination path
dest = 'D:/Pycharm projects/GeeksforGeeks/dst'
# Copying the contents from Source
# to Destination without some
# specified files or directories
shutil.copytree(src, dest, ignore = shutil.ignore_patterns('*.txt', 'a'))
输出: