17

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
  • 3,682
  • 6
  • 26
  • 40
Wilsonwatson
  • 239
  • 1
  • 3
  • 12

2 Answers2

25

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
  • 158,047
  • 31
  • 244
  • 289
shaktimaan
  • 1,406
  • 12
  • 12
6

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
  • 13,413
  • 9
  • 57
  • 71
Alexander Huszagh
  • 10,620
  • 3
  • 32
  • 59