Search code examples
pythonplotdirectoryfigure

Saving figure by creating new folder


I am currently saving my plots in a folder by manually creating it. But I want to create folder automatically and save the figure in it. My current code looks like this

plt.savefig('Figures_Voltage/Pack voltage.png')

Figures_Voltage is the folder which I created manually where there is .py file, but I want that folder to be created by Python. Can anyone help me please. Thanks in advance


Solution

  • You can check if folder doesn't exists and create it

    import os
    
    if not os.path.exists('Figures_Voltage'):
        os.mkdir('Figures_Voltage')
    

    If you try to create when it already exists then it will raise error.


    Or use makedirs with exist_ok=True to skip it if folder already exists (without raising error)

    os.makedirs('Figures_Voltage', exist_ok=True)    
    

    makedirs can also create folder/subfolder/subsubfolder at once.