Jacobian
Jacobian

Reputation: 10802

Copying a file to an existing directory results in IOError [Error 21] is a directory

I get this error:

IOError [Error 21] is a directory

when I try to copy a file to an existing directory. I do it like this:

shutil.copyfile(src, dst)

where src is a file and dst is an existing directory. What I'm doing wrong?

Upvotes: 13

Views: 19686

Answers (3)

Zernach
Zernach

Reputation: 41

See code snippet to see how the source is the path to a file, AND the destination is also a path to a file (that doesn't yet exist until you run this function).

for file in orig_files:
    shutil.copyfile(SOURCE_PATH + file_name, DEST_PATH + file_name)

Upvotes: 2

John Estess
John Estess

Reputation: 636

You're using the wrong function. You might want "copy":

https://docs.python.org/2/library/shutil.html

Upvotes: 11

boaz_shuster
boaz_shuster

Reputation: 2925

You have already answered yourself in the question.

dst should be the path to the copied file. So if you want to copy the file to /var/lib/my/ and your file is called f1 then dst should be /var/lib/my/f1.txt

Try to use shutil.copy as suggested here by john-estess

shutil.copy(src, dst)

or try to fix this using the following snippet

shutil.copyfile(src, '%s/%s' % (dst, src.split('/')[-1]))

Assuming src is the path of the file you want to copy, such as /var/log/apache/access.log, and dst is the path to the directory, where you want to copy the file, for example, /var/lib/my then the new destination is /var/lib/my/access.log.

Upvotes: 11

Related Questions