Search code examples
pythondirectoryfile-copyingfile-not-found

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


I want to copy a file to a new non-existing folder:

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)
        

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/
         
   

The code works well, but copyfile raises this error:

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

   

I don't know why not the file is not copied?


Solution

  • The destination path you printed is not what you actually passed to makedirs. The terminal subfolder was not created because you passed the parent of output. But that was not necessary, because output is derived from destination_path, which is already the (absolute) parent of the relevant folder. So all you really need is this:

    makedirs(output, exist_ok=True)