ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

python文件移动的方法

2026/9/13 14:39:52 拓冰建站 浏览量
python文件移动的方法

以下是Python中移动文件到指定目录的几种实现方法:

方法一:使用shutil模块的move函数

import shutil
import osdef move_file(source_path, destination_path):shutil.move(source_path, destination_path)

方法二:使用os模块的rename函数

import osdef move_file(source_path, destination_path):os.rename(source_path, destination_path)

方法三:逐字节拷贝文件并删除源文件

import osdef 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 subprocessdef move_file(source_path, destination_path):subprocess.run(['mv', source_path, destination_path])