【问题标题】:Create directory recursively in python for linux在python for linux中递归创建目录
【发布时间】:2018-01-15 04:01:59
【问题描述】:

我正在尝试使用 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,上面的选项在这个版本中不起作用?如果不是,什么是替代解决方案?

【问题讨论】:

  • exist_ok 在 3.2 版中是“新”

标签: python linux python-2.7


【解决方案1】:

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)

【讨论】:

  • 不,这不一样。
  • @wim,真的吗?为什么不?我错过了什么?
  • 例如,如果存在同名文件(不是目录)。
  • 从技术上讲,该检查是否适用于路径的每个部分。
  • 这段代码有一个竞争条件(另一个进程可以在这个进程的系统调用之间执行一个系统调用来检查是否存在并创建一个条目)。一种更强大的方法是尝试创建 eaoh 目录,并捕获“目录已存在”的错误。处理“名称存在但不是目录”是一个有趣的挑战。
猜你喜欢
  • 1970-01-01
  • 2011-03-20
  • 2011-10-10
  • 2012-06-12
  • 2011-09-08
  • 1970-01-01
  • 2011-07-28
  • 2016-10-23
相关资源
最近更新 更多