我的部分功能似乎无法正常工作。它说该目录不存在,但是我试图将其保存在一个新目录下。我只是不知道我在做什么错。我知道如何制作目录和文件(我认为)。
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
答案 0 :(得分:1)
ds = str(d.year)+'/'+str(d.month)
--> 2018/10
该目录无效。 实际上是两个目录。
使用os.makedirs
递归创建它们。