首页 文章

通过Python创建文件和目录

提问于
浏览
17

我在创建目录然后打开/创建/写入指定目录中的文件时遇到问题 . 原因似乎不清楚 . 我正在使用os.mkdir()和

path=chap_name
print "Path : "+chap_path                       #For debugging purposes
if not os.path.exists(path):
    os.mkdir(path)
temp_file=open(path+'/'+img_alt+'.jpg','w')
temp_file.write(buff)
temp_file.close()
print " ... Done"

我收到了错误

OSError: [Errno 2] No such file or directory: 'Some Path Name'

路径的形式为'带有未转义空格的文件夹名称'

我在这做错了什么?


更新:我尝试运行代码而不创建目录

path=chap_name
print "Path : "+chap_path                       #For debugging purposes
temp_file=open(img_alt+'.jpg','w')
temp_file.write(buff)
temp_file.close()
print " ... Done"

仍然会出错 . 进一步困惑 .


更新2:问题似乎是img_alt,它在某些情况下包含'/',这会导致麻烦 .

所以我需要处理'/' . 反正有没有逃脱'/'或删除唯一的选择?

2 回答

  • 53
    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)
    

    关键是使用 os.makedirs 代替 os.mkdir . 它是递归的,即它生成所有中间目录 . 见http://docs.python.org/library/os.html

    在存储二进制(jpeg)数据时,以二进制模式打开文件 .

    作为回应 Edit 2 ,如果img_alt有时包含'/':

    img_alt = os.path.basename(img_alt)
    
  • 0
    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
    

相关问题