Copy a file from one location to another in Python

robster picture robster · Oct 17, 2018 · Viewed 47.1k times · Source

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.

Answer

Psytho picture Psytho · Oct 17, 2018

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 destionation path usin 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))