我有一个文件的路径存储在一个变量(比如)filePath 中.我想将该特定文件复制到 Python 脚本中的另一个特定文件夹.
I have the path of a file stored in a variable (say) filePath. I would like to copy that particular file to another specific folder within a Python script.
我试过了
folderPath = (os.getcwd() + "/folder_name/") #to get the path of the folder
shutil.copyfile(filePath, folderPath)
但是我得到一个错误IOError: [Errno 21] Is a directory
.
我该如何解决这个问题?
How can I solve this ?
我的问题似乎与 如何复制python中的文件?.但实际上,我想将文件复制到 文件夹/目录,而该问题的大多数答案都提到将一个文件复制到另一个 文件.
My question might seem to be a duplicate of How do I copy a file in python? . But actually, I want to copy a file to a folder/directory whereas most answers to that question mention copying one file to another file.
使用 shutil.copy(filePath, folderPath)
而不是 shutil.copyfile()
.这将允许您指定一个文件夹作为目标并复制包含权限的文件.
Use shutil.copy(filePath, folderPath)
instead of shutil.copyfile()
. This will allow you to specify a folder as the destination and copies the file including permissions.
shutil.copy(src, dst, *, follow_symlinks=True)
:
将文件 src 复制到文件或目录 dst.src 和 dst 应该是字符串.如果 dst 指定一个目录,该文件将使用来自 src 的基本文件名复制到 dst.返回新创建文件的路径.
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() 复制文件数据和文件的权限模式(参见 os.chmod()).其他元数据,如文件的创建和修改时间,不会被保留.要保留原始文件的所有元数据,请改用 copy2().
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()
本身中也记录的复制差异:
See the difference in copying also documented in shutil.copyfile()
itself:
shutil.copyfile(src, dst, *, follow_symlinks=True)
:
复制名为 src 的文件的内容(无元数据)到名为 dst 的文件 并返回 dst.src 和 dst 是以字符串形式给出的路径名.dst 必须是完整的目标文件名;查看 shutil.copy() 以获取接受目标目录路径的副本.如果 src 和 dst 指定相同的文件,则会引发 SameFileError.
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
这篇关于如何将文件复制到 Python 脚本中的特定文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!