首页 > 解决方案 > shutil.copy() 在起点和终点之间出现错误:FileNotFoundError: [WinError 3] 系统找不到指定的路径

问题描述

我在两个文件夹之间进行复制,源文件夹包含多个子目录,而目标文件夹是一个空文件夹。我使用 shutil.copy() 在我的 glob 中遇到了一些错误:

def copy_files(old_dir, new_dir) -> str:
    for files in old_dir.rglob('*.xlsx'):   #iterate through directory
       if files.match("string_title"):   #filter results matching "string title"
           new_path= new_dir.joinpath(files)   #join file name to new_dir
           if Path.exists(new_path):   #if file already exists in new_dir, pass
               pass
           else:   #if file doesn't exist in new_dir, copy old file to new
               try:
                   shutil.copy(files, new_path, follow_symlinks=True)
               except OSError as e:   #if FileNotFound or other OSError, raise
                   raise e

我的目录中存在的子文件夹出现错误,但显示为“FileNotFoundError:[WinError 3] 系统找不到指定的路径”。

此外,我将以下打印语句结果应用于我的代码,并且位于 If else 语句的上方:

"file is: \\user\name\origin\file.xlsx"
"new_dir is: \\user\name\destination"
"new_path is: \\user\name\origin\file.xlsx"

似乎 new_dir.joinpath(files) 没有按预期工作,因为我希望找到更接近"\user\name\destination\file.xlsx"的东西

我将如何更改它以防止错误?

标签: pythonfilecopyshutil

解决方案


推荐阅读