簡體   English   中英

OSError:[Errno 2]沒有這樣的文件或目錄:'39'

[英]OSError: [Errno 2] No such file or directory: '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' 但是我正在處理器中創建目錄,然后為什么會收到這樣的錯誤。

問題是您的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM