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

Python复制目录时仅复制子目录未复制根目录下文件问题求助

Kodi connman目录全量复制代码修复方案

问题原因

现有代码仅对遍历到的子目录执行了copytree复制逻辑,未处理根目录下的普通文件,因此独立文件无法被复制。

修改后代码

import os
import shutil
import xbmcaddon

# 原有参数定义保持不变
drive = xbmcaddon.Addon().getSetting('Drive')
connman = 'connman/'
src_network = '/storage/.cache/'

# 定义源和目标的根路径
src_connman = os.path.join(drive, connman)
dst_connman = os.path.join(src_network, connman)

# 提前创建目标根目录,避免复制文件时路径不存在报错
os.makedirs(dst_connman, exist_ok=True)

for item in os.listdir(src_connman):
    src_path = os.path.join(src_connman, item)
    dst_path = os.path.join(dst_connman, item)
    # 处理子目录
    if os.path.isdir(src_path):
        try:
            # Python3.8及以上版本可添加dirs_exist_ok=True参数支持覆盖已有目录
            shutil.copytree(src_path, dst_path)
        except Exception as e:
            log(("copytree", e, src_path, dst_path))
    # 处理普通文件
    elif os.path.isfile(src_path):
        try:
            # copy2会保留文件权限、修改时间等元数据,适合配置文件复制
            shutil.copy2(src_path, dst_path)
        except Exception as e:
            log(("copy file", e, src_path, dst_path))

调整说明

  • 新增普通文件的判断分支,使用shutil.copy2完成单文件复制,适配connman配置文件的元数据保留需求
  • 提前创建目标路径的connman根目录,避免单文件复制时因目标路径不存在报错
  • 统一使用os.path.join拼接路径,避免不同系统路径分隔符差异导致的异常
  • 如果需要覆盖目标路径已有的同名目录,可在shutil.copytree参数中添加dirs_exist_ok=True(要求Python3.8及以上版本)

内容的提问来源于stack exchange,提问作者kodi User

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:36:06