Reading a file using a relative path in a Python project

Relative paths are relative to current working directory. If you do not want your path to be relative, it must be absolute. But there is an often used trick to build an absolute path from current script: use its __file__ special attribute: from pathlib import Path path = Path(__file__).parent / “../data/test.csv” with path.open() as f: … Read more

Importing module from string variable using “__import__” gives different results than a normal import statement

The __import__ function can be a bit hard to understand. If you change i = __import__(‘matplotlib.text’) to i = __import__(‘matplotlib.text’, fromlist=[”]) then i will refer to matplotlib.text. In Python 3.1 or later, you can use importlib: import importlib i = importlib.import_module(“matplotlib.text”) Some notes If you’re trying to import something from a sub-folder e.g. ./feature/email.py, the … Read more

Importing a library from (or near) a script with the same name raises “AttributeError: module has no attribute” or an ImportError or NameError

This happens because your local module named requests.py shadows the installed requests module you are trying to use. The current directory is prepended to sys.path, so the local name takes precedence over the installed name. An extra debugging tip when this comes up is to look at the Traceback carefully, and realize that the name … Read more

Import paths – the right way?

What is the entry point for your program? Usually the entry point for a program will be at the root of the project. Since it is at the root, all the modules within the root will be importable, provided there is an __init__.py file in them. So, using your example: my_project/ main.py package1/ __init__.py module1 … Read more