Why is the current directory misaligned between the .py and .ipynb files?

Asked 1 years ago, Updated 1 years ago, 199 views

In order to move directories and save csv data, I have tried and tried many things with ipynb files.
I was able to confirm that ipynb works fine, so I ran a full copy of the code into the py file and got an error saying that the directory was not found.
So when I checked the current directory of ipynb and py (sample.ipynb, sample.py), I found that it was one tier off.

The code you executed for directory verification is as follows:

importos
print(os.getcwd())
os.chdir('../')
print(os.getcwd())

The results are as follows:

sample.ipynb

 d:\Data\XXX\Python
d:\Data\XXX

sample.py

D:\Data\XXX
D:\Data

It is true that the directories for both files are in the same hierarchy (see below).

D:
- - Data
   XXXX
      Yes - Python
         --sample.ipynb
         -- sample.py

As for execution, it works just by changing "..." to "." when moving, but I can't help but worry that the directory is out of alignment even though it is in the same hierarchy.
Why does this happen?

Additional
Both were done in VSCode.
The .py file clicked Start Debugging in VSCode

The settings.json are as follows.

settings.json

{
    "workbench.colorTheme": "Default Dark+",
    "python.linting.flake8Enabled": true,
    "editor.formatOnSave": true,
    "workbench.iconTheme": "material-icon-theme",
    "launch": {
    
        "configurations": [ ],
        "compounds": [ ]
    }
}

python

2022-10-22 09:15

2 Answers

For .ipynb (Jupyter Notebook, JupiterLab):

Not the directory where the Notebook is located The directory where Jupiter started (directory of Jupiter Kernel) is the current directory.
(In the following cases, you will be in the position where you started the jupyter lab)

$cd/home/USER/lang/Python
$ jupyter lab

.py is the same for
(Python/sample.py runs, but getcwd() is where Python ran.)

-home
   USER
      --lang
         Yes - Python
            -- sample.py

$ cd/home/USER/lang/

$ python Python / sample.py
/home/USER/lang
/home/USER

.ipynb in VS Code should be the location of the workspace


2022-10-22 09:15

os.getcwd() returns only the working directory and not necessarily the location where you saved the program you ran.

If you run it in the same directory as the .py file, the results will be the same, but the results will vary depending on how you run it.


2022-10-22 09:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.