Greem666
Greem666

Reputation: 949

shutil copyfile giving Errno 2 on my destination folder

I have written a function like below:

def separate_files(filetree_list, destination):

    from shutil import copyfile
    from os import makedirs
    from os.path import join, exists, commonprefix
    
    try:
        for file in filetree_list:
            dst = join(destination,
                       '\\'.join(file.split(commonprefix(filetree_list))[1].split('\\')[0:-1]))
            if not exists(dst):
                print(dst, " doesn`t exist. Creating...")
                makedirs(dst)
                print(exists(dst), ". Path created.")
            print(file)
            copyfile(file, dst)
    except:
        print("Moving files has FAILED.")
    else:
        print("Moving files was SUCCESSFUL.")

When I call it with a "filetree_list" list containing a single element and destination prepared with os.path.join:

filetree_list = ['C:\\Users\\<username>\\staging_folder\\folder_1\\filename.xlsx'] 
destination = os.path.join(staging_dir, 'Sorted', 'Unwanted_files')

I get the following error:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-29-c3525a60c859> in <module>()
     14         print(exists(dst), ". Path created.")
     15     print(file)
---> 16     copyfile(file, dst)

    C:\ProgramData\Anaconda3\lib\shutil.py in copyfile(src, dst, follow_symlinks)
    119     else:
    120         with open(src, 'rb') as fsrc:
--> 121             with open(dst, 'wb') as fdst:
    122                 copyfileobj(fsrc, fdst)
    123     return dst

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\<username>\\staging_folder\\Sorted\\Unwanted_files\\'

What is strange about it (and it is driving me insane at the moment), is that this folder definitely exists, and has been created by the "if not exists(dst)" block in separate_files function - I can even see it in the Windows Explorer!

To add insult to injury, when I run this function with the same destination argument but multiple strings in a list, it does what I expect and there are no errors!

Can anyone offer any insight into what am I doing wrong in here?

Upvotes: 2

Views: 7740

Answers (2)

Jozef
Jozef

Reputation: 13

noted one thing, if the file path is large than 259 character, it will give same error.

Upvotes: 0

melpomene
melpomene

Reputation: 85767

https://docs.python.org/3/library/shutil.html#shutil.copyfile:

shutil.copyfile(src, dst, *, follow_symlinks=True)

Copy the contents (no metadata) of the file named src to a file named dst and return dst. src and dst are path names given as strings. dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path.

You're trying to pass a directory as dst to copyfile. That doesn't work.

Upvotes: 2

Related Questions