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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52851994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:12:50  来源:igfitidea点击:

Copy a file from one location to another in Python

pythonpython-3.xfile-copying

提问by robster

I have a list called fileListcontaining thousands of filenames and sizes something like this:

我有一个名为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']

I want to copy the files using fileList[0] as the source but to another whole destination. Something like:

我想使用 fileList[0] 作为源将文件复制到另一个完整的目的地。就像是:

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.

我可以看看什么才能让它发挥作用?我在 Mac 和 Linux 上使用 Python 3。

回答by Psytho

You have to give a full nameof 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)

您可以使用获取文件名os.path.basename(path),然后使用使用构建目标路径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))

回答by Rakesh

Use os.path.basenameto get the file name and then use it in destination.

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

回答by Z Yoder

You could just use the shutil.copy() command:

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

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

[来自 Python 3.6.1 文档。我试过了,它有效。]

回答by Thom

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.

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