I want to know how to import a local file in different scenarios: importing a single .py
file, an entire folder (as a package), loading a file dynamically at runtime based on user input, or importing just one specific function from another file.
What’s the correct way to handle each of these?
If I have a simple file like utils.py in the same folder, I just use:
import utils
or
from utils import my_function
That’s the cleanest approach when everything’s in the same directory. Just make sure the file is in the same folder or Python’s path.
When dealing with a folder of files, I treat it like a package. I include an __init__.py
file inside the folder and then import like this:
from myfolder.module import function_name
It’s super useful for structuring larger projects. If the folder isn’t in the current path, I’ll use sys.path.append()
to add it manually.
In cases where I don’t know the filename until runtime (like user input), I go with:
import importlib
module = importlib.import_module('my_script')
module.run()
That way, I can load scripts on the fly, and it still feels clean. Just be cautious with input, you don’t want to dynamically import malicious files by accident.