Python 检查目录是否存在,然后在必要时创建它并将图形保存到新目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31008598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:19:59  来源:igfitidea点击:

Python check if a directory exists, then create it if necessary and save graph to new directory?

python

提问by Wilsonwatson

so I want this to be independent of the computer the code is used on, so I want to be able to create a directory in the current directory and save my plots to that new file. I looked at some other questions and tried this (I have two attempts, one commented out):

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

    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

I get the error :

我收到错误:

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

I also want to know if my idea of saving it in the directory will work, which I haven't been able to test because of the errors I've been getting in the above portion.

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

采纳答案by shaktimaan

os.mkdirs()is not a method in os module. if you are making only one direcory then use os.mkdir()and if there are multiple directories try using os.makedirs()Check Documentation

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

回答by Alexander Huszagh

You are looking for either:

您正在寻找:

os.mkdir

os.mkdir

Or os.makedirs

或者 os.makedirs

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

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

os.makedirs makes all the directories, so if I type in shell (and get nothing):

os.makedirs 创建所有目录,所以如果我输入 shell(并且什么也没得到):

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

It has made all the directories and subdirectories. os.mkdir would throw me an error, because there is no "alex/is/making/a" directory.

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