30

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,850
  • 6
  • 28
  • 43
Wilsonwatson
  • 361
  • 1
  • 4
  • 12

2 Answers2

32

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
  • 168,929
  • 32
  • 262
  • 294
shaktimaan
  • 1,639
  • 13
  • 13
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
  • 16,909
  • 11
  • 66
  • 79
Alexander Huszagh
  • 12,117
  • 3
  • 36
  • 66