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.

Vivi
  • 4,070
  • 6
  • 29
  • 44
Wilsonwatson
  • 379
  • 1
  • 4
  • 13

2 Answers2

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

kindall
  • 178,883
  • 35
  • 278
  • 309
shaktimaan
  • 1,769
  • 13
  • 14
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.

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
Alex Huszagh
  • 13,272
  • 3
  • 39
  • 67