Python中的文件复制函数
发布时间:2023-08-12 19:52:42
在Python中,可以使用多种方法来实现文件的复制操作。下面将介绍几种常用的文件复制函数。
1. 使用open()函数和read()、write()方法:
def copy_file(src, dest):
with open(src, 'rb') as fsrc:
with open(dest, 'wb') as fdest:
fdest.write(fsrc.read())
该函数使用二进制模式读取源文件的内容,并将其写入目标文件。
2. 使用shutil模块的copyfile()函数:
import shutil
def copy_file(src, dest):
shutil.copyfile(src, dest)
该函数可以直接将源文件的内容复制到目标文件。
3. 使用shutil模块的copy()函数:
import shutil
def copy_file(src, dest):
shutil.copy(src, dest)
该函数可以复制源文件的内容和权限,并将其放置到目标位置。
4. 使用shutil模块的copy2()函数:
import shutil
def copy_file(src, dest):
shutil.copy2(src, dest)
该函数与copy()函数类似,但还会尝试保留源文件的元数据,如文件权限和时间戳信息。
5. 使用os模块的read()和write()函数:
import os
def copy_file(src, dest):
with open(src, 'rb') as fsrc:
with open(dest, 'wb') as fdest:
for chunk in iter(lambda: fsrc.read(4096), b''):
fdest.write(chunk)
该函数使用迭代方式读取源文件的内容,并将其写入目标文件。
这些函数中,src参数表示源文件的路径,dest参数表示目标文件的路径。在调用这些函数时,可以根据实际情况选择适合的函数来实现文件的复制操作。
