Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Errno 20: Not a directory when saving into zip file

When I try to save a pyplot figure as a jpg, I keep getting a directory error saying that the given file name is not a directory. I am working in Colab. I have a numpy array called z_img and have opened a zip file.

import matplotlib.pyplot as plt
from zipfile import ZipFile

zipObj = ZipFile('slices.zip', 'w') # opening zip file
plt.imshow(z_img, cmap='binary')

The plotting works fine. I did a test of saving the image into Colab’s regular memory like so:

plt.savefig(str(ii)+'um_slice.jpg')

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And this works perfectly, except I am intending to use this code in a for loop. ii is an index to differentiate between each image, and several hundred images would be created so I want them going in the zipfile. Now when I try adding the path to the zipfile:

plt.savefig('/content/slices.zip/'+str(ii)+'um_slice.jpg')

I get: NotADirectoryError: [Errno 20] Not a directory: ‘/content/slices.zip/150500um_slice.jpg’

I assume it’s because the {}.jpg string is a filename, and not a directory per se. But I am quite new to Python, and don’t know how to get the plot into the zip file. That’s all I want. Would love any advice!

>Solution :

From the docs, matplotlib.pyplot.savefig accepts a binary file-like object. ZipFile.open creates binary file like objects. These two have to get todgether!

with zipobj.open(str(ii)+'um_slice.jpg', 'w') as fp: 
    plt.savefig(fp)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading