Creating files and directories via Python

前端 未结 2 894
面向向阳花
面向向阳花 2020-12-08 07:21

I\'m having trouble creating a directory and then opening/creating/writing into a file in the specified directory. The reason seems unclear to me. I\'m using os.mkdir() and

2条回答
  •  余生分开走
    2020-12-08 08:03

    import os
    
    path = chap_name
    
    if not os.path.exists(path):
        os.makedirs(path)
    
    filename = img_alt + '.jpg'
    with open(os.path.join(path, filename), 'wb') as temp_file:
        temp_file.write(buff)
    

    Key point is to use os.makedirs in place of os.mkdir. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html

    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)
    

提交回复
热议问题