Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new folder to the directory you are in in jupyter notebook

I am working with python and jupyter notebook, and I am writing code to save images to a folder. However, I am getting the error 'FileNotFoundError: [Errno 2] No such file or directory: 'plots/plot0.jpg'. I believe this is because I do not have a folder 'plots' in the current directory, and I was wondering how do add this. I have attached some code to see what is in the directory and how I am saving this image. Thank you!

img.save("plots/plot" + str(j) + ".png")

I ran this code:

import os
os.listdir()

and 'plots' was not in there, does this mean I need to create a new folder, and if so, how do I do that? Thank you!

'


2 Answers

It appears you are trying to save the image file to a folder named "plot" which doesn't exist. You can use os.makedirs() to create this "plot" folder

For example:

import os
os.makedirs("plots")

This will create a new directory named "plots" in the current directory from which you have called this python script.

You could then check to see if the folder has been created in your directory by using os.listdir()

Another way to can add a new directory without importing any modules is by using bash/cmd commands.

!mkdir plot

Adding subdirectories can be done:

!mkdir data/plot

In windows:

!mkdir data\plot

Similairly, any bash command can be run a Jupyter Notebook by adding ! before the command.

!cwd or !ls when in a Linux environment and !dir in Windows.

like image 34
YScharf Avatar answered Nov 02 '25 23:11

YScharf