首页 > 解决方案 > os.makedirs 不在 Windows 上创建文件夹

问题描述

我正在使用 python 3.7 和以下命令创建一个适用于 linux 但不适用于 windows 的目录:

       try:
        #shutil.rmtree('../../dist')
        os.makedirs('../../dist')
    except OSError as e:
        print("fffffffffffffffffffffffffffff")
        print(e)
        if e.errno != errno.EEXIST:
            raise

这是我在 Windows 上运行它时遇到的错误:

fffffffffffffffffffffffffffff
[WinError 183] Cannot create a file when that file already exists: 
'../../dist'

而且根本没有 dist 文件夹,我不知道那个错误是什么

任何的想法?

标签: pythonwindowspython-3.x

解决方案


根据 OP 的要求将评论作为答案:

这里的问题是您提供的是相对于脚本的路径,但相对路径是相对于进程的工作目录进行解释的,这通常与脚本位置完全不同。该目录相对于工作目录已经存在,但是您正在查看相对于脚本的路径,并且(正确地)在那里找不到任何东西。

如果必须相对于脚本创建目录,请将代码更改为:

scriptdir = os.path.dirname(__file__)
# abspath is just to simplify out the path so error messages are plainer
# while os.path.join ensures the path is constructed with OS preferred separators
newdir = os.path.abspath(os.path.join(scriptpath, '..', '..', 'dist'))
os.makedirs(newdir)

推荐阅读