gpt4 book ai didi

python - 在python中为linux递归创建目录

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:45:12 25 4
gpt4 key购买 nike

我正在尝试使用 Python 脚本递归地创建目录,但出现错误。

代码:

import os
a = "abc"
os.makedirs('/root/test_{}'.format(a), exist_ok=True)

错误:

Traceback (most recent call last):
File "mk.py", line 3, in <module>
os.makedirs('/root/test_{}'.format(a), exist_ok=True)
TypeError: makedirs() got an unexpected keyword argument 'exist_ok'

我正在使用 python2.7,上面的选项在这个版本中不起作用?如果不是,替代解决方案是什么?

最佳答案

os.makedirs()是正确的函数,但在 Python 2 中没有参数 exist_ok。而是使用 os.path.exists()喜欢:

if not os.path.exists(path_to_make):
os.makedirs(path_to_make)

请注意,这与 Python3 中 exist_ok 标志的行为不完全匹配。更接近匹配的是:

if os.path.exists(path_to_make):
if not os.path.isdir(path_to_make):
raise OSError("Cannot create a file when that file already exists: "
"'{}'".format(path_to_make))
else:
os.makedirs(path_to_make)

关于python - 在python中为linux递归创建目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48256779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com