Python中_IO模块实现文件的拷贝与移动的方法分享
发布时间:2024-01-06 05:01:53
在Python中,可以使用shutil模块实现文件的拷贝与移动操作。shutil是Python内置的文件和目录操作模块,提供了一套简单易用的函数,用于处理文件、复制文件和文件夹、以及与文件有关的操作。
下面是使用shutil模块实现文件的拷贝与移动的方法,以及相关的使用示例。
1. 拷贝文件:shutil.copy(src, dst, *, follow_symlinks=True)
这个函数将文件src拷贝到指定的目标位置dst。如果dst指定的路径是一个目录,src会被拷贝到该目录下,并保留原文件名。如果dst指定的路径已存在,会抛出FileExistsError错误。
使用示例:
import shutil # 拷贝文件到指定目录 src_file = "path/to/source/file.txt" dst_dir = "path/to/destination/folder" shutil.copy(src_file, dst_dir) # 拷贝文件并给定新的文件名 src_file = "path/to/source/file.txt" dst_file = "path/to/destination/new_file.txt" shutil.copy(src_file, dst_file) # 拷贝文件并保留原文件名 src_file = "path/to/source/file.txt" dst_dir = "path/to/destination/folder" shutil.copy(src_file, dst_dir)
2. 移动文件:shutil.move(src, dst, copy_function=copy2)
这个函数将文件src移动到指定的目标位置dst。如果dst指定的路径是一个目录,src会被移动到该目录下,并保留原文件名。如果dst指定的路径已存在,会抛出FileExistsError错误。
使用示例:
import shutil # 移动文件到指定目录 src_file = "path/to/source/file.txt" dst_dir = "path/to/destination/folder" shutil.move(src_file, dst_dir) # 移动文件并给定新的文件名 src_file = "path/to/source/file.txt" dst_file = "path/to/destination/new_file.txt" shutil.move(src_file, dst_file) # 移动文件并保留原文件名 src_file = "path/to/source/file.txt" dst_dir = "path/to/destination/folder" shutil.move(src_file, dst_dir)
以上就是使用shutil模块实现文件的拷贝与移动的方法和使用示例。通过这些方法,我们可以方便地对文件进行拷贝和移动操作。需要注意的是,在进行文件拷贝和移动操作时,需要保证相关的源文件和目标路径是存在的,否则会抛出相应的异常。
