copyfile raises "FileNotFoundError: [Errno 2] No such file or directory"

copyfile raises "FileNotFoundError: [Errno 2] No such file or directory"

我想将文件复制到一个新的不存在的文件夹中:

import pandas as pd
from imutils import paths
from os import path, makedirs
from shutil import copyfile
from pathlib import Path
import os

imagePaths = list(paths.list_images('/x/x/x/x/DatasetNiiCleanedcopyB/test/NCP/'))
df= pd.read_csv(r"file.csv")

    # loop over the image paths
    for imagePath in imagePaths:
        word='/'.join(imagePath.split('/')[7:])
        #search in dataframe
        if((df['imgpath'].str.contains(word)).any()):
            imPath = Path(imagePath)
            destination_path= imPath.parent.absolute()
            output = str(destination_path).replace('DatasetNiiCleanedcopyB', 'DatasetNiiCleanedcopyB3')+'/' 
            print('source path is'+ imagePath)
            print('destination path is'+ output)   
            makedirs(path.dirname(path.abspath(output)), exist_ok=True)
            copyfile(imagePath, output)
        

输出:

source path is=  /x/x/x/x/DatasetNiiCleanedcopyB/test/NCP/61/1255/0065.png
    
destination path is= /x/x/x/x/DatasetNiiCleanedcopyB3/test/NCP/61/1255/
         
   

代码运行良好,但 copyfile 引发此错误:

FileNotFoundError: [Errno 2] No such file or directory: /x/x/x/x/DatasetNiiCleanedcopyB3/test/NCP/61/1255/

   

不知道为什么没有复制文件?

您打印的目标路径不是您实际传递给makedirs的路径。未创建终端子文件夹,因为您传递了 outputparent。但这不是必需的,因为 output 派生自 destination_path,它已经是相关文件夹的(绝对)父级。所以你真正需要的是:

makedirs(output, exist_ok=True)