如何创建新目录并在 python 中写入新的 'wb' 文件?

How do I make a new directory and write a new 'wb' file in python?

我的这部分功能似乎无法正常工作。它说该目录不存在,但我正在尝试将其保存在一个新目录下。我只是不知道我做错了什么。我知道如何制作目录和文件(我认为)。

import os
from datetime import date

def save_image(d, image):
    """
    Save binary image on disk.

    Use the date of the image (d) to create a directory structure 
    (year/month) if it doesn't exist already,
    then save the binary image under its corresponding year and month using 
    the date (d) + '.jpg' as a file name

    HINT: Binary data can be written to files in a similar way to how 
    strings are written to files.
    Use 'wb' (write binary) instead of 'w' in the file open clause (i.e. 
    open(file_path, 'wb'))

    args:
        d: date object containing image date
        image: binary image itself

    returns:
        file_path: where the image was saved

    examples:
        if d = 2017-8-21, the image will be saved as: 2017/8/2017-8-21.jpg
        if d = 1998-4-15, the image will be saved as: 1998/4/1998-4-15.jpg
    """

    ds = str(d.year)+'/'+str(d.month)
    file_path = ds+'/'+str(d)+'.jpg'

至此file_path的写法与示例类似,但在此之后不会创建新目录。它只是给出一个错误,说目录不存在。我很困惑为什么它不让我创建一个新目录然后将图像保存在新文件下。有什么想法吗?

    os.mkdir(ds)
    with open(file_path, 'wb') as file:
        file.write(image)
    return file_path
ds = str(d.year)+'/'+str(d.month)
--> 2018/10

这不是一个有效的目录。 那实际上是两个目录。

使用os.makedirs递归创建它们。