Jupyter Notebook
Absolute File Path
The __file__
attribute is not available in Jupyter notebooks. It’s a built-in attribute in Python scripts that contains the path of the script that is currently being executed.
In a Jupyter notebook, you can use the os and IPython libraries to get the notebook’s path:
import os
from IPython.core.getipython import get_ipython
# Get the current notebook's path
= os.path.join(os.getcwd(), get_ipython().starting_dir)
notebook_path
# Specify the relative path to the directory
= "data/test_data"
relative_path
# Construct the absolute path
= os.path.join(notebook_path, relative_path)
file_dir
# assert the file_dir exists
assert os.path.isdir(file_dir)
# list 5 files in the file_dir
5] os.listdir(file_dir)[:
def get_absolute_path_in_notebook(relative_path: str) -> str:
# Get the current notebook's path
= os.path.join(os.getcwd(), get_ipython().starting_dir)
notebook_path
# Construct the absolute path
= os.path.join(notebook_path, relative_path)
absolute_path
return absolute_path
= get_absolute_path_in_notebook(file_path_relative)
file_path_abs
assert os.path.isfile(file_path_abs), f"File not found: {file_path_abs}"
VSCode mode
settings.json
"notebook.lineNumbers": "on",
"notebook.output.wordWrap": true
Display local variables
use vars()
to display local variables or attributes.
try:
del obj
print("Deleted obj")
except NameError:
pass
if 'obj' in locals():
del obj
assert 'obj' not in locals(), "obj not deleted"