【发布时间】: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