【问题标题】:copyfile raises "FileNotFoundError: [Errno 2] No such file or directory"复制文件引发“FileNotFoundError:[Errno 2] 没有这样的文件或目录”
【发布时间】:2021-11-11 14:50:27
【问题描述】:

我想将一个文件复制到一个新的不存在的文件夹中:

import pandas as pd
from imutils import paths
from os import path, makedirs
from shutil import copyfile
from pathlib import Path
import os

imagePaths = list(paths.list_images('/x/x/x/x/DatasetNiiCleanedcopyB/test/NCP/'))
df= pd.read_csv(r"file.csv")

    # loop over the image paths
    for imagePath in imagePaths:
        word='/'.join(imagePath.split('/')[7:])
        #search in dataframe
        if((df['imgpath'].str.contains(word)).any()):
            imPath = Path(imagePath)
            destination_path= imPath.parent.absolute()
            output = str(destination_path).replace('DatasetNiiCleanedcopyB', 'DatasetNiiCleanedcopyB3')+'/' 
            print('source path is'+ imagePath)
            print('destination path is'+ output)   
            makedirs(path.dirname(path.abspath(output)), exist_ok=True)
            copyfile(imagePath, output)
        

输出:

source path is=  /x/x/x/x/DatasetNiiCleanedcopyB/test/NCP/61/1255/0065.png
    
destination path is= /x/x/x/x/DatasetNiiCleanedcopyB3/test/NCP/61/1255/
         
   

代码运行良好,但copyfile 引发此错误:

FileNotFoundError: [Errno 2] No such file or directory: /x/x/x/x/DatasetNiiCleanedcopyB3/test/NCP/61/1255/

   

不知道为什么不复制文件?

【问题讨论】:

  • 复制时,您还需要在目标中提供文件名。关于这个问题,它有格式问题,并且代码部分包含语法错误,因为缩进在 Python 中很关键。
  • 您打印的目标路径不是您传递给makedirs 的路径:即未创建1255 子文件夹。
  • 这能回答你的问题吗? How do I copy a file in Python?
  • @MatBBastos 否,因为错误与目录有关,而不是文件。
  • 要清楚,你应该简单地做makedirs(output, exist_ok=True)。 (请注意,output 已经是绝对的,因为它派生自 destination_path)。

标签: python directory file-copying file-not-found


【解决方案1】:

您打印的目标路径不是您实际传递给makedirs 的路径。由于您传递了output,因此未创建终端子文件夹。但这不是必需的,因为output 派生自destination_path,它已经是相关文件夹的(绝对)父级。所以你真正需要的是:

makedirs(output, exist_ok=True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 2022-11-13
    • 2019-11-03
    • 2021-08-24
    • 2021-03-07
    • 2015-06-09
    相关资源
    最近更新 更多