parentDirectory
subdr1
-testfile.txt
subdr2
childdir
-file.json
-file2.pickle
-fileOpener.py
I would like to read the file.json from fileOpener.py in Python using:
with open("./childdir/file.json", 'r') as f:
But I’m getting FileNotFoundError.
FileNotFoundError: [Errno 2] No such file or directory: './childdir/file.json'
Would anyone mind solving this issue? I’m using WINDOWS operating system.
3
Answers
First of all which OS are you using ? since windows uses
and UNIX based OSes use
/
Bast approach would be to use path from os module like this:
This is a better approach because it is platform independent since it creates the path appropriately based on the OS you are on.
This is because the file you want to open is in the subdirectory of your current working directory(where the python file is present).
You need to consider 2 things here,
Depends on the OS which you’re using, it’s either ‘/’ for UNIX-based &
” for Windows-based as separator in the file’s path
we can either use the absolute path of the file and mode to open the file
or with the path sub-module of that os module.
or
If you run
fileOpener.py
within thesubdir2
then all is well. The problem happens when you are not insubdir2
. Here is the solution:Since
pathlib
is cross-platform, this code should work under Windows. I tested it under Mac and linux.