A couple of ways exist.
One particular to Jupyter is to use the
%cd magic to change the current working directory. Note that it is different than
!cd. And in fact often the magic command on
cd is added automatically in most versions and interfaces, see about
automagic here. (Your mileage may vary here and that is why I prefer to be explicit using
%cd even when
cd will suffice.)
So using you
%cd you can direct the current working directory in your notebook to the new location and act like you are working inside there with
Alternatively, you can use the absolute path to the file or relative path to the file as part of the string where you specify the name for the file in your
open() command. In the case of relative, it would be relative what it shows in your notebook at the time if you run a cell with
%pwd as the content.
%pwd is the magic command for
print working directory, see here.
Below is demonstration of these concepts expanded from the first one I posted. It makes a new directory called
othdir below whatever is the current working directory in your system and saves the text file in that new directory by switching to that as the working directory. Then the working is switched again back to the starting directory, above the new directory. From there the
open() function is run and the relative path is included as part of the file path and name information provided to
open() so that the text file is opened from within the new directory, even though at the time the working directory is the same as when all this began.
s='''This is a test
This is still a test
Really this is a test
%store s >demofile.txt
h = open("othdir/demofile.txt", "r")
for line in h: