python怎么复制文件
原创Python怎样复制文件
在Python中,复制文件是一项非常基础且常用的操作。可以使用多种方法来实现这一功能,最常见的是使用标准库中的shutil
模块。下面将介绍怎样使用这个模块来复制文件。
使用shutil模块复制文件
shutil
模块提供了copyfile()
函数,它可以简洁地复制文件内容从一个文件到另一个文件。以下是shutil.copyfile()
函数的基本使用方法:
import shutil
# 源文件路径
source_path = 'source_file.txt'
# 目标文件路径
destination_path = 'destination_file.txt'
# 复制文件
shutil.copyfile(source_path, destination_path)
复制文件同时保持元数据
如果你愿望在复制文件内容的同时,也复制源文件的权限位、最后访问时间、最后修改时间等元数据,可以使用shutil.copy2()
函数:
import shutil
source_path = 'source_file.txt'
destination_path = 'destination_file.txt'
# 复制文件及元数据
shutil.copy2(source_path, destination_path)
使用open函数和read/write方法复制文件
除了shutil
模块,还可以使用Python内置的open
函数结合文件读/写方法来手动复制文件:
# 打开源文件并读取内容,然后打开目标文件并写入内容
with open('source_file.txt', 'rb') as source_file: # 'rb' 代表"只读二进制"
with open('destination_file.txt', 'wb') as destination_file: # 'wb' 代表"只写二进制"
# 如果文件不是太大,可以一次性读取整个文件
content = source_file.read()
destination_file.write(content)
# 如果文件很大,可以分块读取和写入
# for chunk in iter(lambda: source_file.read(4096), b''):
# destination_file.write(chunk)
注意事项
在复制文件时,以下是一些需要注意的事项:
- 确保你有权限读取源文件和写入目标文件。
- 目标文件的路径如果已存在,将会被覆盖,请小心操作。
- 如果文件较大,使用分块读取和写入可以节省内存。
使用上述任何一种方法,都可以轻松实现文件复制功能,让文件操作变得更加灵活和方便。