31

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.

3
  • 1
    There's os.mkdir, and os.makedirs. There's no os.mkdirs. (As the error message already explained to you.) Commented Jun 23, 2015 at 16:43
  • okay got it, sorry I'm pretty new to programming Commented Jun 23, 2015 at 16:50
  • 2
    I use if not os.path.exists(new_path): \ os.makedirs(new_path) Commented Feb 2, 2021 at 22:23

2 Answers 2

33

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

Sign up to request clarification or add additional context in comments.

Comments

7

You are looking for either:

os.mkdir

Or os.makedirs

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

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

$ 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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.