I’m working on a Colab notebook that needs to be shared with other people. The problem is that I want to use relative paths for accessing files in my mounted Google Drive instead of absolute paths. This way the code won’t break when others run it from different locations.
Right now I have to use full paths like /gdrive/My Drive/Projects/data_analysis/files/datasets/csv_files but I want to use something like ./files/datasets/csv_files since my notebook is located in /gdrive/My Drive/Projects/data_analysis.
I was thinking about using sys.path.append to add the notebook’s current directory to the Python path, but I’m not sure how to do this without hardcoding another absolute path. Even if I manage to add it to the path, I’m still confused about how to actually use relative paths in my code cells.
I found some solutions online that suggest ways to get the notebook path, but they seem unreliable and only work if your notebook has a unique name in Drive.
Any suggestions on how to make this work properly?
I create a config cell that finds the notebook’s location dynamically - no hardcoded paths. After mounting Drive, I use os.path.dirname(os.path.abspath('')) to grab the current directory and build my base path from there. Here’s the thing: Colab runs from a predictable spot relative to your notebook when you open it straight from Drive. I set up a BASE_PATH variable that everyone can reference. So if your notebook’s in the data_analysis folder, you’d do BASE_PATH = '/content/drive/MyDrive/Projects/data_analysis' then use os.path.join(BASE_PATH, 'files', 'datasets', 'csv_files') for file access. Works great across different users on my team projects.
I’ve hit this same problem tons of times with shared Colab notebooks. Here’s what works: set up a working directory right at the start using os.chdir() after you mount the drive. Use os.getcwd() right after mounting to see where you are, then navigate to your project folder. I always create a setup cell that mounts the drive, switches to the project directory, and then everything else just uses relative paths. The trick is getting everyone to put the shared notebook in the same spot in their Drive. Also throw in a quick check in your setup cell to make sure the expected folders actually exist before you start running your analysis.
Honestly, just switch to pathlib instead of os.path - it’s way cleaner. After mounting your drive, import it with from pathlib import Path and set your base: base = Path('/content/drive/MyDrive/Projects/data_analysis'). Then you can do base / 'files' / 'datasets' / 'csv_files' and it handles path joining automatically. Plus it works cross-platform if anyone runs this locally later.