在Python中将文件从一个位置复制到另一个位置

问题描述 投票:1回答:4

我有一个名为fileList的列表,其中包含数千个文件名和大小,如下所示:

['/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']

我想使用fileList [0]作为源复制文件,但是要复制到另一个目标。就像是:

copyFile(fileList[0], destinationFolder)

并将文件复制到该位置。

当我这样尝试时:

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

我收到如下错误:

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

为了让这个工作起作用,我能看到什么?我在Mac和Linux上使用Python 3。

python python-3.x file-copying
4个回答
8
投票

您必须提供目标文件的全名,而不仅仅是文件夹名称。

您可以使用qazxsw poi获取文件名,然后使用qazxsw poi构建目标路径

os.path.basename(path)

4
投票

使用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))

2
投票

您可能需要从源字符串中删除文件名并将其放在目标路径后面,因此它是一个完整的文件路径。


1
投票

你可以使用shutil.copy()命令:

EG

os.path.basename

[来自Python 3.6.1文档。我试过这个并且它有效。]

© www.soinside.com 2019 - 2024. All rights reserved.