【问题标题】:Python check if a directory exists, then create it if necessary and save graph to new directory? [duplicate]Python 检查目录是否存在,然后在必要时创建它并将图形保存到新目录? [复制]
【发布时间】:2015-09-09 14:17:38
【问题描述】:

所以我希望它独立于使用代码的计算机,所以我希望能够在当前目录中创建一个目录并将我的图保存到那个新文件中。我查看了其他一些问题并尝试了这个(我有两次尝试,一次注释掉了):

    import os
    from os import path
    #trying to make shift_graphs directory if it does not already exist:

    if not os.path.exists('shift_graphs'):
        os.mkdirs('shift_graphs')

    plt.title('Shift by position on '+str(detector_num)+'-Detector')
    #saving figure to shift_graphs directory
    plt.savefig(os.path.join('shift_graphs','shift by position on '+str(detector_num)+'-detector'))
    print "plot 5 done"
    plt.clf

我得到错误:

AttributeError: 'module' object has no attribute 'mkdirs'

我还想知道我将其保存在目录中的想法是否可行,由于我在上述部分中遇到的错误,我无法对其进行测试。

【问题讨论】:

  • os.mkdiros.makedirs。没有os.mkdirs。 (正如已经向您解释过的错误消息。)
  • 好的,抱歉,我对编程很陌生
  • 我用if not os.path.exists(new_path):\os.makedirs(new_path)

标签: python


【解决方案1】:

os.mkdirs() 不是 os 模块中的方法。 如果您只制作一个目录,则使用os.mkdir(),如果有多个目录,请尝试使用os.makedirs() 检查Documentation

【讨论】:

    【解决方案2】:

    您正在寻找:

    os.mkdir

    os.makedirs

    https://docs.python.org/2/library/os.html

    os.makedirs 创建所有目录,所以如果我输入 shell(什么都没有):

    $ ls
    $ python
    >>> import os
    >>> os.listdir(os.getcwd())
    []
    >>> os.makedirs('alex/is/making/a/path')
    >>> os.listdir(os.getcwd())
    ['alex']
    

    它已经制作了所有的目录和子目录。 os.mkdir 会给我一个错误,因为没有“alex/is/making/a”目录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-18
      • 2015-12-06
      • 2012-10-23
      • 2015-10-05
      • 2011-05-12
      相关资源
      最近更新 更多