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

明明存在的文件为何无法用Python脚本复制?

文件复制失败问题排查

错误根源

报错FileNotFoundError: [Errno 2] No such file or directory: ''的核心原因是:
当目标文件仅传入**纯文件名(不含路径)**时,os.path.split(dst)会返回空字符串作为父目录(比如os.path.split("new_file.zip")得到('', 'new_file.zip')),而调用os.makedirs('')会直接触发错误——空字符串不是合法的目录路径。

另外,代码中传入的源文件是Path对象,虽然os模块多数函数能兼容,但os.path.getsize(src)存在潜在的兼容性问题,建议统一路径处理方式。

修复方案

方案1:修复目标目录判断逻辑

在创建父目录前,先判断父目录路径是否为空,为空则跳过创建步骤:

def copyFile(src, dst, buffer_size=10485760, perserveFileDate=True):
    # ... 其他代码 ...
    dstParent, dstFileName = os.path.split(dst)
    # 仅当父目录存在且不存在时才创建
    if dstParent and not os.path.exists(dstParent):
        os.makedirs(dstParent)
    # ... 其他代码 ...

方案2:改用Path对象处理路径(更简洁)

利用pathlib的API替代字符串路径操作,避免手动拆分路径的错误:

import os
import shutil
from pathlib import Path

def copyFile(src, dst, buffer_size=10485760, perserveFileDate=True):
    src_path = Path(src)
    dst_path = Path(dst)
    
    # 创建目标父目录(自动忽略空目录场景,exist_ok=True避免重复创建报错)
    dst_path.parent.mkdir(parents=True, exist_ok=True)
   
    # 优化缓冲区大小
    file_size = src_path.stat().st_size
    buffer_size = min(buffer_size, file_size) if file_size > 0 else 1024
   
    if src_path.samefile(dst_path):
        raise shutil.Error(f"`{src_path}` and `{dst_path}` are the same file")
    for fn in [src_path, dst_path]:
        try:
            st = fn.stat()
        except OSError:
            pass
        else:
            if shutil.stat.S_ISFIFO(st.st_mode):
                raise shutil.SpecialFileError(f"`{fn}` is a named pipe")
    with open(src_path, 'rb') as fsrc:
        with open(dst_path, 'wb') as fdst:
            shutil.copyfileobj(fsrc, fdst, buffer_size)
   
    if perserveFileDate:
        shutil.copystat(src_path, dst_path)

方案3:直接使用shutil内置函数

Python内置的shutil.copy2()已经实现了文件复制+保留元数据的功能,完全可以替代自定义的copyFile函数,简化代码:

if __name__ == "__main__":  
    full_file_name_str = Path(pdb_dir_str, "pdb1a6j.ent.gz")
    print(full_file_name_str)
    # 如果目标需要创建父目录,先处理路径
    dst_path = Path("new_file.zip")
    dst_path.parent.mkdir(parents=True, exist_ok=True)
    shutil.copy2(full_file_name_str, dst_path)

验证

修改后运行脚本,即可正常完成文件复制操作,不会再触发空目录的创建错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:30:53