Search code examples
pythondataframefiledirectorymove

python moving files to folder depending on df values


I am new to path use and moving files in python. My objective is to sort my files in different "classes folders" to classify them after. To sort them, I added a column with the curent location of each file. I am trying to create move all these files in the target folder (different for each file)

image_path is the curent location of my files (all in the same directory, including filename and extension) ipath is the target folder for the files (including filename and extension) I already created all destination directories for all files preview of my df

here is my code:

#initialisation of variables used
ip = ''
imp = ''
for image_name in rkt_merged.image_name:
    #attribution of path to variables
    ip = ipath
    imp = image_path
    #
    filePath = shutil.move(image_path, ipath)

The error received is the following, which i do not understand "FileNotFoundError: [Errno 2] No such file or directory: '' I suspect my variables are not getting the values from my df.

I also tried the following loop with enumerate:

for ipath, image_path in enumerate(rkt_merged.image_name):
    filePath = shutil.move(image_path, ipath)

And received the following error : rename: dst should be string, bytes or os.PathLike, not int

When displaying my variable, everything seems correct. thank you for your help


Solution

  • The error message FileNotFoundError: [Errno 2] No such file or directory: '' means that the file you are trying to move does not exist. I think that, in you case, the file path is empty, which is why you are getting this error.

    If that is the case, to fix it, you need to make sure that the image_path variable is set to the correct file path. You can do this by iterating over the rows of your DataFrame and getting the value of the image_name column for each row. For example:

    import shutil
    
    # Get the current working directory
    cwd = os.getcwd()
    
    # Iterate over the rows of the DataFrame
    for index, row in rkt_merged.iterrows():
        # Get the image name
        image_name = row['image_name']
    
        # Get the current file path
        image_path = os.path.join(cwd, image_name)
    
        # Get the target file path
        ipath = os.path.join(cwd, 'target_folder', image_name)
    
        # Move the file
        shutil.move(image_path, ipath)
    

    This code will iterate over the rows of your DataFrame and move each file to the target folder.

    Note that you may need to modify the cwd variable to the correct working directory. You can also modify the target_folder variable to the desired target folder.

    I hope this helps!