Importing a Python File by Name

January 25th, 2024
python, tech
Let's say you have a python script:
2024-01-24--evaluate-chimeras.py
And you want to pull a section of it out into a separate file:
2024-01-25--strand-split-artifacts.py
You would hope you could just do something like:
import "/path/to/2024-01-25--strand-split-artifacts.py"
But this doesn't work: import wants a module name, not a filename. The simplest way I know to import a python file from a path is:
import sys
import importlib

sys.path.append("/path/to/")
ssa = importlib.import_module("2024-01-25--strand-split-artifacts")
There are a lot of complicated ways to do this, some of which avoid needing to add something to sys.path, but for quick one-off research code better to keep it simple.

Comment via: facebook, lesswrong, mastodon

Recent posts on blogs I like:

Starting With Chords

A lot of people play fiddle. Basically nobody starts by learning chords before learning melodies. But that's actually how I learned. I started with chords. One of the nice things about learning to play violin this way is that you can go busking even…

via Anna Wise's Blog Posts November 15, 2024

Stuffies

I have some stuffies and I just have a bunny. Bunny is a rabbit. Woof is a seal. My favorite stuffie is bun bun. I play with my stuffies. Sometimes I jump up with them and I roll them. I can just throw them in the air when I want to play bthululubp wi…

via Nora Wise's Blog Posts November 15, 2024

You Can Buy A Malaria Net

2024 election takes

via Thing of Things November 6, 2024

more     (via openring)