2012-07-28 197 views
15

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

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,它在某些情况下包含'/',这会导致麻烦。

所以我需要处理'/'。 无论如何逃避'/'或删除唯一的选择?

+1

'路径+ '/' + img_alt +” jpg'' ..最好使用'OS .path.join()'这里 – Levon 2012-07-28 11:29:55

+0

@Ayos。发布您正在使用的路径 – 2012-07-28 11:52:50

+0

我没有看到'path'和'chap_path'和'img_alt'是如何关联的。 – tiwo 2012-07-28 11:54:28

回答

48
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.mkdir使用os.makedirs。它是递归的,即它生成所有中间目录。请参阅http://docs.python.org/library/os.html

当您存储二进制(jpeg)数据时,以二进制模式打开文件。

响应于编辑2,如果img_alt有时有 '/' 在它:

img_alt = os.path.basename(img_alt) 
+0

我明白这是做到这一点的语法正确方式,但是您能否真正告诉我为什么发生错误?为什么我们使用'wb'而不是'w'? – ffledgling 2012-07-28 11:35:58

+1

如果由于父目录尚不存在而无法到达要创建的目标目录(路径中最右侧的目录),则会引发OSError。 os.mkdir不是递归的,所以它不会沿路径创建所有需要的目录。 os.makedirs确实。 – 2012-07-28 11:38:52

+1

'b'在文本和二进制文件表现不同的平台上有意义。引用[文档](http://docs.python.org/tutorial/inputoutput.html),“Windows上的Python区分了文本和二进制文件;文本文件中的行尾字符会自动更改当数据被读取或写入时略微。“ – tiwo 2012-07-28 11:40:57

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 
+0

请参阅原始问题和已接受的答案,它明确指出'os.mkdir'不起作用,并且接受的答案指出将使用'os.mkdirs'。 – ffledgling 2017-08-31 20:04:43