How to add a folder to Python path?

Viewed 58

Basically, I can only reference my other files as modules when they are in a very specific location:

C:\Users\Dave\Desktop\Programming\Python. 

If I want to create a new folder for a large project with multiple modules, say

C:\Users\Dave\Desktop\Programming\Python\Project1,

I can no longer import any modules and keep getting a ModuleNotFoundError. I've looked into it and it seems I need to add that folder to the Python Path somehow, but I couldn't find any answers on how to do it. My computer runs on Windows 10 if that matters.

1 Answers

I think the immediate solution to your problem/the answer to your question would be to use sys.path.append() at the top of your script.

import sys
sys.path.append("<ABSOLUTE/PATH/TO/YOUR/CUSTOM/MODULES/FOLDER>")

import custom_module

This isn't an ideal solution for any kind of prod use, however. Based on what you wrote in your question, this may not be what you're looking for. More info might help to craft a more stable solution:

  • Are you using virtual environments when running python? Do you just run python script.py or is there a specific version of python you're using that's installed elsewhere than the common C:\Program Files\Python?

  • When you say that you work on a project with multiple modules, does that mean there are custom modules that you/someone wrote or is it just that that project uses non-standard library modules, i.e. you had to pip install them?

  • Can we get an example of the code you're running and the folder structure of your project/where the modules are that you need?

Related