You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的shutil仅移动文件夹内容而非文件夹本身?

如何仅移动文件夹内的内容到目标目录?

你当前用shutil.move(str(source_directory), str(dest_dir))会把整个源目录(比如home/abc)移动到目标目录下,所以才出现home/qwerty/abc的结构。要把源目录内的内容直接移到目标目录,需要遍历源目录下的所有条目并逐个移动。

实现代码

import os
import shutil

def move_dir_contents(source_dir, dest_dir):
    # 确保目标目录存在,不存在则创建
    os.makedirs(dest_dir, exist_ok=True)
    
    # 遍历源目录下的所有文件和子目录
    for item in os.scandir(source_dir):
        # 拼接目标路径
        dest_item_path = os.path.join(dest_dir, item.name)
        # 移动当前条目到目标目录
        shutil.move(item.path, dest_item_path)
    
    # 可选:删除空的源目录(如果不需要保留)
    os.rmdir(source_dir)
    return dest_dir

# 调用示例
source_directory = "/home/abc"
dest_dir = "/home/qwerty"
result_dir = move_dir_contents(source_directory, dest_dir)

关键说明

  • os.makedirs(dest_dir, exist_ok=True):确保目标目录存在,避免移动操作因目录不存在报错。
  • os.scandir(source_dir):比os.listdir更高效,直接返回包含文件/目录路径和属性的对象,简化路径拼接。
  • 逐个移动条目:这样源目录内的dir1、dir2会直接被移到home/qwerty下,符合你的预期结构。

处理同名冲突(可选)

如果目标目录下已存在同名文件/目录,shutil.move在Windows下会直接报错,Unix系统下会覆盖文件或合并目录。如果需要自定义冲突处理逻辑,可以添加判断:

for item in os.scandir(source_dir):
    dest_item_path = os.path.join(dest_dir, item.name)
    if os.path.exists(dest_item_path):
        # 示例:给重名条目添加编号后缀
        base_name, ext = os.path.splitext(item.name)
        count = 1
        while os.path.exists(os.path.join(dest_dir, f"{base_name}_{count}{ext}")):
            count += 1
        dest_item_path = os.path.join(dest_dir, f"{base_name}_{count}{ext}")
    shutil.move(item.path, dest_item_path)

内容的提问来源于stack exchange,提问作者Fábio Pires

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 23:45:12