28

I have a list called fileList containing thousands of filenames and sizes something like this:

['/home/rob/Pictures/some/folder/picture one something.jpg', '143452']
['/home/rob/Pictures/some/other/folder/pictureBlah.jpg', '473642']
['/home/rob/Pictures/folder/blahblahpicture filename.jpg', '345345']

I want to copy the files using fileList[0] as the source but to another whole destination. Something like:

copyFile(fileList[0], destinationFolder)

and have it copy the file to that location.

When I try this like so:

for item in fileList:
    copyfile(item[0], "/Users/username/Desktop/testPhotos")

I get an error like the following:

with open(dst, 'wb') as fdst:
IsADirectoryError: [Errno 21] Is a directory: '/Users/username/Desktop/testPhotos'

What could be something I could look at to get this working? I'm using Python 3 on a Mac and on Linux.

2
  • 1
    Looking at the comment of psytho, have a look at the os package for path manipulation. Commented Oct 17, 2018 at 9:56
  • 3
    docs.python.org/2/library/shutil.html the copy accepts folders as destination Commented Oct 17, 2018 at 9:59

4 Answers 4

38

You could just use the shutil.copy() command:

e.g.

    import shutil

    for item in fileList:
        shutil.copy(item[0], "/Users/username/Desktop/testPhotos")

[From the Python 3.6.1 documentation. I tried this and it works.]

Sign up to request clarification or add additional context in comments.

2 Comments

I just realized this was added as a comment above. Sorry for the duplication.
this is a more exact answer to the OPs question.
29

You have to give a full name of the destination file, not just a folder name.

You can get the file name using os.path.basename(path) and then build the destination path using os.path.join(path, *paths)

for item in fileList:
    filename = os.path.basename(item[0])
    copyfile(item[0], os.path.join("/Users/username/Desktop/testPhotos", filename))

1 Comment

Simple and elegant. Thank you. It makes perfect sense and the example was excellent. Much appreciated
10

Use os.path.basename to get the file name and then use it in destination.

import os
from shutil import copyfile


for item in fileList:
    copyfile(item[0], "/Users/username/Desktop/testPhotos/{}".format(os.path.basename(item[0])))

1 Comment

if you use shutil why not use copy which directly allows to put a directory as destination?
2

You probably need to cut off the file name from the source string and put it behind the destination path, so it is a full file path.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.