如何在Python脚本中将文件复制到特定文件夹? [英] How to copy a file to a specific folder in a Python script?

查看:918
本文介绍了如何在Python脚本中将文件复制到特定文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将文件的路径存储在变量(例如)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]是目录

如何我解决了这个问题?

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)

复制内容(不包含元数据)的文件的strong>转换为名为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脚本中将文件复制到特定文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆