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

This question already has an answer here:

  • How do I copy a file in python? 14 answers

  • 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):

    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

    See the difference in copying also documented in shutil.copyfile() itself:

    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 must be a file, not a directory. The error says it all. Do something like:

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

    改变你的代码如下:

    folderPath = os.path.join('folder_name', os.path.basename(filePath))
    shutil.copyfile(filePath, folderPath)
    
    链接地址: http://www.djcxy.com/p/42320.html

    上一篇: 用Python复制和重命名excel文件

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