Creating files and directories via Python

import os

path = chap_name

if not os.path.exists(path):

filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:

Key point is to use os.makedirs in place of os.mkdir. It is recursive, i.e. it generates all intermediate directories. See

Open the file in binary mode as you are storing binary (jpeg) data.

In response to Edit 2, if img_alt sometimes has “” in it:

img_alt = os.path.basename(img_alt)

Leave a Comment