How do I import a python file through a path?


I am trying to make it so when this runs it runs the newest version in the list.

Here is the directory I want:

ClockOS: (the file I am starting at)
      Version 0.1.1: (Ignore because tis an older version)
      Version 0.1.2: (The one I want to run/import)

I have tried loading through os.dir, and using sys.path, and adding an empty
Anyone know how to get this working?
My code:

import os
import re
import sys

versionList = []

for filename in os.listdir('Versions'):
    if filename.startswith('Version'):
        print(f"Loaded {filename}")

def major_minor_micro(version):
    major, minor, micro ='(\d+)\.(\d+)\.(\d+)', version).groups()

    return int(major), int(minor), int(micro)

latest = str(max(versionList, key=major_minor_micro))

print("Newest Version: ", latest)


sys.path.insert(1, latest)

import main

Lastly, I need this to work on both windows and linix, if that’s possible.


You need to use importlib to do what you want. Here is an example on how to import my_function from a file:

import importlib
spec = importlib.util.spec_from_file_location('some_module_name', filename)
mod = importlib.util.module_from_spec(spec)

Probably the question is a duplicate of Import arbitrary python source file. (Python 3.3+)

Answered By – Peter Mukhachev

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published