rob*_*ter 1 python file-copying python-3.x
我有一个名为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']
Run Code Online (Sandbox Code Playgroud)
我想使用fileList [0]作为源复制文件,但是要复制到另一个目标.就像是:
copyFile(fileList[0], destinationFolder)
Run Code Online (Sandbox Code Playgroud)
并将文件复制到该位置.
当我这样尝试时:
for item in fileList:
copyfile(item[0], "/Users/username/Desktop/testPhotos")
Run Code Online (Sandbox Code Playgroud)
我收到如下错误:
with open(dst, 'wb') as fdst:
IsADirectoryError: [Errno 21] Is a directory: '/Users/username/Desktop/testPhotos'
Run Code Online (Sandbox Code Playgroud)
为了让这个工作起作用,我能看到什么?我在Mac和Linux上使用Python 3.
Z Y*_*der 24
你可以只使用 shutil.copy() 命令:
例如
import shutil
for item in fileList:
shutil.copy(item[0], "/Users/username/Desktop/testPhotos")
Run Code Online (Sandbox Code Playgroud)
[来自 Python 3.6.1 文档。我试过了,它有效。]
您必须提供目标文件的全名,而不仅仅是文件夹名称.
您可以使用文件名os.path.basename(path),然后使用destionation路径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))
Run Code Online (Sandbox Code Playgroud)
使用os.path.basename来获取文件名,然后在目的地使用它。
import os
from shutil import copyfile
for item in fileList:
copyfile(item[0], "/Users/username/Desktop/testPhotos/{}".format(os.path.basename(item[0])))
Run Code Online (Sandbox Code Playgroud)