21
votes

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.

4
Looking at the comment of psytho, have a look at the os package for path manipulation.mikuszefski
docs.python.org/2/library/shutil.html the copy accepts folders as destinationmikuszefski

4 Answers

29
votes

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.]

27
votes

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))
8
votes

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])))
2
votes

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.