Creating files and directories via Python

前端 未结 2 884
面向向阳花
面向向阳花 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)
    
    0 讨论(0)
  • 2020-12-08 08:25
        import os
        os.mkdir('directory name') #### this command for creating directory
        os.mknod('file name') #### this for creating files
        os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 
    
    0 讨论(0)
提交回复
热议问题