详解Python 移动或复制文件和目录

  • Post category:Python

Python 提供了 shutil 模块,用于在文件系统中复制文件和目录。该模块有两个主要的函数,copy() 和 copy2(),它们可以用来复制文件和目录。

复制文件

要复制文件,可以使用 copy() 或 copy2() 函数。

copy() 函数原型如下:

shutil.copy(src, dst, *, follow_symlinks=True)

其中,src 参数是源文件的路径, dst 参数是目标文件的路径。如果目标文件已经存在,则将被覆盖。follow_symlinks 参数指示是否应该跟随符号链接。

示例:

import shutil

# 复制文件
src_file = 'source.txt'
dst_file = 'destination.txt'
shutil.copy(src_file, dst_file)

复制目录

要复制目录,可以使用 copytree() 函数。该函数将目录和其中的所有文件递归地复制到目标目录中。

copytree() 函数原型如下:

shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,
                 ignore_dangling_symlinks=False, dirs_exist_ok=False)

其中,src 参数是源目录的路径, dst 参数是目标目录的路径。symlinks、ignore、copy_function 和 ignore_dangling_symlinks 参数是可选的。

示例:

import shutil

# 复制目录
src_folder = 'source_folder'
dst_folder = 'destination_folder'
shutil.copytree(src_folder, dst_folder)

移动文件或目录

要移动文件或目录,可以使用 move() 函数。

move() 函数原型如下:

shutil.move(src, dst, copy_function=copy2)

其中,src 参数是源文件或目录的路径, dst 参数是目标文件或目录的路径。copy_function 参数是可选的。

示例:

import shutil

# 移动文件
src_file = 'source.txt'
dst_file = 'new_location/destination.txt'
shutil.move(src_file, dst_file)

# 移动目录
src_folder = 'source_folder'
dst_folder = 'new_location/destination_folder'
shutil.move(src_folder, dst_folder)

以上就是 Python 移动或复制文件和目录的完整攻略,希望能对你有所帮助。