Python脚本中:如何将文件复制到的特定文件夹?

How to copy a file to a specific folder in a Python script?

本问题已经有最佳答案,请猛点这里访问。

我有一个存储在变量(比如)file path中的文件的路径。我想将该特定文件复制到Python脚本中的另一个特定文件夹中。

我试过

1
2
folderPath = (os.getcwd() +"/folder_name/") #to get the path of the folder
shutil.copyfile(filePath, folderPath)

但我得到了一个错误IOError: [Errno 21] Is a directory

我怎么解决这个问题?

我的问题似乎是如何在python中复制文件的副本?. 但实际上,我想把一个文件复制到一个文件夹/目录中,而这个问题的大多数答案都提到了将一个文件复制到另一个文件中。


shutil.copy(filePath, folderPath)代替shutil.copyfile()。这将允许您指定一个文件夹作为目标,并复制包含权限的文件。

shutil.copy(src, dst, *, follow_symlinks=True):

Copies the file src to the file or directory dst. src and dst should be strings. If dst specifies a directory, the file will be copied into dst using the base filename from src. Returns the path to the newly created file.

...

copy() copies the file data and the file’s permission mode (see os.chmod()). Other metadata, like the file’s creation and modification times, is not preserved. To preserve all file metadata from the original, use copy2() instead.

https://docs.python.org/3/library/shutil.html_shutil.copy

参见shutil.copyfile()中记录的复制差异:

shutil.copyfile(src, dst, *, follow_symlinks=True):

Copy the contents (no metadata) of the file named src to a file named dst and return dst. src and dst are path names given as strings. dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path. If src and dst specify the same file, SameFileError is raised.

https://docs.python.org/3/library/shutil.html shutil.copyfile文件


folderpath必须是文件,而不是目录。错误说明一切。做一些类似的事情:

1
shutil.copyfile(filePath, folderPath+'/file_copy.extension')


更改代码如下:

1
2
folderPath = os.path.join('folder_name', os.path.basename(filePath))
shutil.copyfile(filePath, folderPath)