Using .pth Files to Globally Import Custom Python Utility Modules
This article explains how to place a folder of reusable Python utility scripts into a .pth file within the site‑packages directory so that the modules can be imported in any project without manually copying files or modifying sys.path, streamlining development across virtual environments.
During years of coding, the author collected many handy utility functions—such as network request retry, time format conversion, and regex generation—into several .py files stored in a folder named my_awesome_util .
Because the folder is not published on PyPI or GitHub, each new project requires copying the entire my_awesome_util directory, which leads to duplicated code and maintenance headaches.
Manually adding the folder to sys.path in every project's entry file is also undesirable, as it prevents full automation.
The solution is to leverage Python's .pth files. By creating a plain‑text .pth file inside the interpreter's site-packages directory and writing the absolute path of my_awesome_util on a single line, Python automatically adds that folder to its module search path.
For example, a file named xxxx.pth placed in site-packages might contain:
my_awesome_utilAfter this, any Python session started from any location can simply import time_util (or other utilities) without extra configuration. Screenshots illustrate the folder structure and the successful import.
Multiple lines can be added to a single .pth file, each pointing to a different utilities folder, allowing batch inclusion of many modules.
This approach also helps when working with multiple virtual environments: by adding the site-packages path of one environment to a .pth file in another, you can share third‑party libraries without reinstalling them.
To locate the site-packages directory, run the following Python code:
import sysconfig
print(sysconfig.get_path('purelib'))The resulting path is shown in the accompanying screenshot.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.