Python如何检查一个目录是否存在,如果不存在就创建它,并将图表存到新目录中?

13 浏览
0 Comments

Python如何检查一个目录是否存在,如果不存在就创建它,并将图表存到新目录中?

这个问题已经有答案了

如何安全地创建一个目录(可能包括中间目录)?

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

    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'

我还想知道我的保存目录的想法是否可行,但由于上面部分中的错误,我没有能够测试它。

admin 更改状态以发布 2023年5月22日
0
0 Comments

您正在寻找以下内容之一:

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" 目录。

0
0 Comments

os.mkdirs()不是os模块中的一个方法。如果您只是创建一个目录,请使用os.mkdir(),如果有多个目录,则尝试使用os.makedirs()。请查看文档

0