python - Shutil copyfile 在我的目标文件夹上给出 Errno 2

标签 python file-transfer shutil

我编写了一个如下所示的函数:

def separate_files(filetree_list, destination):

    from shutil import copyfile
    from os import makedirs
    from os.path import join, exists, commonprefix
    
    try:
        for file in filetree_list:
            dst = join(destination,
                       '\\'.join(file.split(commonprefix(filetree_list))[1].split('\\')[0:-1]))
            if not exists(dst):
                print(dst, " doesn`t exist. Creating...")
                makedirs(dst)
                print(exists(dst), ". Path created.")
            print(file)
            copyfile(file, dst)
    except:
        print("Moving files has FAILED.")
    else:
        print("Moving files was SUCCESSFUL.")

当我使用包含单个元素和使用 os.path.join 准备的目标的“filetree_list”列表调用它时:

filetree_list = ['C:\\Users\\<username>\\staging_folder\\folder_1\\filename.xlsx'] 
destination = os.path.join(staging_dir, 'Sorted', 'Unwanted_files')

我收到以下错误:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-29-c3525a60c859> in <module>()
     14         print(exists(dst), ". Path created.")
     15     print(file)
---> 16     copyfile(file, dst)

    C:\ProgramData\Anaconda3\lib\shutil.py in copyfile(src, dst, follow_symlinks)
    119     else:
    120         with open(src, 'rb') as fsrc:
--> 121             with open(dst, 'wb') as fdst:
    122                 copyfileobj(fsrc, fdst)
    123     return dst

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\<username>\\staging_folder\\Sorted\\Unwanted_files\\'

它的奇怪之处(此刻让我发疯)是这个文件夹肯定存在,并且是由separate_files函数中的“if not contains(dst)” block 创建的 - 我什至可以看到它位于 Windows 资源管理器中!

雪上加霜的是,当我使用相同的目标参数但列表中存在多个字符串运行此函数时,它会按照我的预期执行并且没有错误!

任何人都可以深入了解我在这里做错了什么吗?

最佳答案

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

shutil.<b>copyfile</b>(<i>src</i>, <i>dst</i>, <i>*</i>, <i>follow_symlinks=True</i>)

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.

您正在尝试将目录传递为 dstcopyfile 。那是行不通的。

关于python - Shutil copyfile 在我的目标文件夹上给出 Errno 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52528910/

相关文章:

Python Shutil.copytree 表示缺少应该复制的目标文件

python - 使用 Shutil.move 移动文件

python - Django 表格 : disable field if booleanfield is checked

image - 通过PhoneGap(iOS)上传后,图像侧向/上下翻转

python - 拥有多个 tf.Graph 有什么意义?

javascript - Cordova FileTransfer 不发送自定义 header

ios - 如何使用 Phonegap Filetransfer 下载图片到 iOS 中的图库

python - 使用python进行异步文件分发

python - 在服务器上找不到文件时阻止代码崩溃的方法?

python - 我如何配置我的 uWsgi 服务器以防止不可读的发布错误?