当前位置: 代码网 > it编程>前端脚本>Python > 利用Python把文件移动到另一个文件夹的方法

利用Python把文件移动到另一个文件夹的方法

2025年10月22日 Python 我要评论
在python中,文件移动可通过shutil.move()函数实现。以下是完整操作指南:基础移动(单个文件)import shutilimport os# 定义源文件和目标路径source_file

在python中,文件移动可通过shutil.move()函数实现。以下是完整操作指南:

基础移动(单个文件)

import shutil
import os

# 定义源文件和目标路径
source_file = '/path/source.txt'
target_folder = '/path/target_folder/'

# 确保目标目录存在
os.makedirs(target_folder, exist_ok=true)

# 执行移动
shutil.move(source_file, target_folder)

批量移动(带文件类型过滤)

import os
import shutil
import glob

source_dir = '/path/source_folder'
target_dir = '/path/target_folder'
os.makedirs(target_dir, exist_ok=true)

# 移动所有.ts文件
for ts_file in glob.glob(os.path.join(source_dir, '*.ts')):
    shutil.move(ts_file, target_dir)

关键特性说明

  • 自动覆盖:目标目录存在同名文件时自动覆盖
  • 目录创建os.makedirs(..., exist_ok=true)自动创建目标目录
  • 跨设备支持:支持不同磁盘分区间的文件移动
  • 错误处理:建议添加try-except捕获filenotfounderror等异常

高级技巧

保留目录结构移动

import os
import shutil

source = '/data/source'
target = '/data/target'

for root, dirs, files in os.walk(source):
    for file in files:
        src_path = os.path.join(root, file)
        rel_path = os.path.relpath(src_path, source)
        target_path = os.path.join(target, rel_path)
        
        os.makedirs(os.path.dirname(target_path), exist_ok=true)
        shutil.move(src_path, target_path)

移动并重命名

shutil.move('/source/file.txt', '/target/renamed_file.txt')

注意事项

  • 移动系统文件时需管理员权限
  • 移动过程中文件被占用会导致操作失败
  • 跨文件系统移动实质是复制+删除
  • 建议先测试shutil.copy2()保留元数据

到此这篇关于利用python把文件移动到另一个文件夹的方法的文章就介绍到这了,更多相关python文件移动到另一个文件夹内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com