2014-12-29 57 views
0

我有以下一段代碼在特定條件下創建一個目錄。OSError:[Errno 2]沒有這樣的文件或目錄:'39'

def create_analysis_folder(self, analysis_id, has_headers): 

     path = None 
     if not os.path.exists(analysis_id): 
      os.makedirs(analysis_id)  
     os.chdir(analysis_id) 
     if has_headers == False: 
      path = os.getcwd() + '/html' 
      return path 
     else: 
      os.makedirs('html') 
      os.chdir('html') 
      shutil.copy("../../RequestURL.js", os.getcwd()) 
      return os.getcwd() 

在執行這給了我行

os.makedirs(analysis_id)

錯誤的錯誤說OSError: [Errno 2] No such file or directory: '39'。但我在處理器中創建一個目錄,那麼爲什麼我會得到這樣的錯誤。

+0

看來你「analysis_id」是數字。嘗試在字符串中轉換它 –

+1

追溯是什麼?在執行'create_analysis_folder'之後不要使用'chdir',你永遠不知道在哪個目錄中。 – Daniel

回答

2

問題是您的chdir,因爲我已經在我的評論中說過。這裏是發生了什麼:

>>> os.makedirs('a/b/c') # create some directories 
>>> os.chdir('a/b/c') # change into this directory 
>>> os.rmdir('../c') # remove the current directory 
>>> os.makedirs('z') # trying to create a directory in a non-existing directory 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/.../python2.7/os.py", line 157, in makedirs 
    mkdir(name, mode) 
OSError: [Errno 2] No such file or directory: 'z' 

正確的方法,來處理這樣的問題是:

BASE_DIR = os.getcwd() # or any other path you want to work with 
def create_analysis_folder(self, analysis_id, has_headers): 
    if not os.path.exists(os.path.join(BASE_DIR, analysis_id)): 
     os.makedirs(os.path.join(BASE_DIR,analysis_id)) 
    path = os.path.join(BASE_DIR, analysis_id, 'html') 
    if has_headers: 
     os.makedirs(path) 
     shutil.copy(os.path.join(BASE_DIR, "RequestURL.js"), path) 
    return path 
相關問題