繁体   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