要将文件从当前位置拷贝到另一个位置,Python 提供了多种简单高效的方法。以下是几种常见的方法及其实现步骤:
1. 使用 shutil.copyfile()
这是最基础的方法,适合拷贝文件内容到目标位置。
示例代码:
import shutil
source_path = 'source_file.txt'
destination_path = 'destination_folder/target_file.txt'
shutil.copyfile(source_path, destination_path)
2. 使用 shutil.copy()
该方法除了拷贝文件内容外,还会保留文件的元数据(如修改时间等)。
示例代码:
import shutil
source_path = 'source_file.txt'
destination_path = 'destination_folder/target_file.txt'
shutil.copy(source_path, destination_path)
3. 使用 shutil.copy2()
类似于 shutil.copy()
,但更适用于需要保留所有文件信息的场景,包括元数据和访问权限。
示例代码:
import shutil
source_path = 'source_file.txt'
destination_path = 'destination_folder/target_file.txt'
shutil.copy2(source_path, destination_path)
4. 使用 shutil.copyfileobj()
适合在两个文件对象之间直接拷贝内容,常用于处理大文件或二进制文件。
示例代码:
import shutil
with open('source_file.txt', 'rb') as src_file, open('destination_file.txt', 'wb') as dst_file:
shutil.copyfileobj(src_file, dst_file)
5. 检查目标文件夹是否存在
在拷贝文件前,建议检查目标文件夹是否存在,若不存在则创建。
示例代码:
import os
import shutil
source_path = 'source_file.txt'
destination_path = 'destination_folder/target_file.txt'
if not os.path.exists(os.path.dirname(destination_path)):
os.makedirs(os.path.dirname(destination_path))
shutil.copy(source_path, destination_path)
总结
根据需求选择合适的方法即可轻松实现文件拷贝。建议使用 shutil.copy2()
,因为它不仅拷贝内容,还保留了文件的完整信息。如果目标文件夹不存在,记得提前创建,以避免运行时错误。