【问题标题】:shutil copyfile giving Errno 2 on my destination foldershutil copyfile 在我的目标文件夹中提供 Errno 2
【发布时间】:2021-08-13 06:14:42
【问题描述】:

我写了如下函数:

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

它有什么奇怪的(现在让我发疯),这个文件夹确实存在,并且是由单独文件函数中的“如果不存在(dst)”块创建的 - 我什至可以看到它在 Windows 资源管理器中!

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

谁能提供任何关于我在这里做错了什么的见解?

【问题讨论】:

  • 糟糕,抱歉 - 函数原型设计阶段的遗留问题。显然,它应该是 copyfile(file, dst) ,而不是 copyfile(file, join(destination, file.split(commonprefix(filetree_list))[1])) 之一。我现在将编辑该更改。
  • 也更新了循环问题 - 对不起,我责怪我从 IDE 技能中复制不当。
  • dst 是文件夹名称。 with open(dst, 'wb') 正在尝试将其作为文件打开(用于写入)。那是行不通的。
  • 嗯,但目标参数不应该是文件夹,而不是文件吗? source 指向一个文件,而 dst 指向这个文件应该存放的文件夹?

标签: python file-transfer shutil


【解决方案1】:

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

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

您正在尝试将目录作为dst 传递给copyfile。这行不通。

【讨论】:

  • 谢谢你 - 为我解决了这个问题。我将 copyfile 行修改为 copyfile(file, os.path.join(dst, filename)) ,现在一切都已修复。
猜你喜欢
  • 2021-07-18
  • 2018-02-25
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
  • 2011-02-28
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多