以下是Python中移动文件到指定目录的几种实现方法:
方法一:使用shutil模块的move函数
import shutil
import os
def move_file(source_path, destination_path):
shutil.move(source_path, destination_path)
方法二:使用os模块的rename函数
import os
def move_file(source_path, destination_path):
os.rename(source_path, destination_path)
方法三:逐字节拷贝文件并删除源文件
import os
def move_file(source_path, destination_path):
with open(source_path, 'rb') as source_file:
with open(destination_path, 'wb') as destination_file:
destination_file.write(source_file.read())
os.remove(source_path)
方法四:使用subprocess模块执行操作系统的移动命令,即采用命令行的方式,
import subprocess
def move_file(source_path, destination_path):
subprocess.run(['mv', source_path, destination_path])