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

标签 python file copy filesystems file-copying

<分区>

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

我试过了

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

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

我该如何解决这个问题?

我的问题似乎与 How do I copy a file in 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

关于python - 如何将文件复制到 Python 脚本中的特定文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45126572/

相关文章:

docker - Docker-从其他工作目录到另一个工作目录的COPY文件不起作用

python - scipy.optimize.curve_fit 无法拟合偏移的倾斜高斯曲线

python - 如何在 Python zeep 中指定 SOAP 服务器 URL

ios - 以编程方式锁定 iOS 设备上的文件

java - 如何仅将 GET_CONTENT 用于音频?

c - 有没有一种方法可以快速确定从(稀疏)文件中读取的 block 是否全为零?

postgresql - 从 CSV 文件更新 PostgreSQL 表

ubuntu - 如何在gedit中选择文本

python - 如何在 Windows 10 中检查特定用户的环境变量?

python - Django 通用关系不起作用