2012-07-28 198 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