26

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
robster
  • 626
  • 1
  • 7
  • 22

4 Answers4

35

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

Z Yoder
  • 509
  • 4
  • 7
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))
Carl Manaster
  • 39,912
  • 17
  • 102
  • 155
Psytho
  • 3,313
  • 2
  • 19
  • 27
  • Simple and elegant. Thank you. It makes perfect sense and the example was excellent. Much appreciated – robster Oct 17 '18 at 10:41
9

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])))
Rakesh
  • 81,458
  • 17
  • 76
  • 113
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.

Thom
  • 157
  • 7