Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 655
Wilsonwatson Avatar asked Jun 23 '15 16:06

Wilsonwatson


People also ask

How do you check if a directory exists in Python and create it?

To create a directory if not exist in Python, check if it already exists using the os. path. exists() method, and then you can create it using the os. makedirs() method.

How do you check if a folder exists and if not create it?

You can use os. path. exists('<folder_path>') to check folder exists or not.

How do you create a folder and save it in Python?

mkdir() os. mkdir() method in Python is used to create a directory named path with the specified numeric mode.


1 Answers

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

like image 81
shaktimaan Avatar answered Sep 20 '22 03:09

shaktimaan