shutil copyfile和[Errno 2]

时间:2018-09-27 03:16:05

标签: python file-transfer

我编写了如下函数:

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.")

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

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\\'

奇怪的是(此刻让我发疯了),这个文件夹确实存在,并且是由eparate_files函数中的“ if not exist(dst)”块创建的-我什至可以看到在Windows资源管理器中!

为了增加伤害,当我使用相同的目标参数但列表中有多个字符串运行此函数时,它会达到我的期望,并且没有错误!

有人能提供我在这里做错什么的任何见解吗?

更新: 更新了上面的代码以反映我的IDE中的功能。纠正了print(file)和copyfile(file,dst)旁边的缩进错误,以将其包含在循环中。 copyfile()的dst参数也已更新为“ dst”,而不是join(destination,file.split(commonprefix(filetree_list))[1])。

1 个答案:

答案 0 :(得分:1)

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

  

shutil.copyfile(src, dst, *, follow_symlinks=True)

     

将名为 src 的文件的内容(无元数据)复制到名为 dst 的文件中,并返回 {{1 }} dst src 是以字符串形式给出的路径名。 dst 必须是完整的目标文件名;在shutil.copy()中查找接受目标目录路径的副本。

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