0

I have the following folder structure and want to find a good way to import python modules.

project1/test/benchmark/benchmark_project1.py

#in benchmark_project1.py
from project1.test.benchmark import *

My question is how to get rid of project1, since it might be renamed to "project2" or something else. I want to use import with absolute path, but don't know a good way to achieve that.

Ramy M. Mousa
  • 5,727
  • 3
  • 34
  • 45
Zack
  • 1,205
  • 2
  • 14
  • 38
  • You might want to look at https://stackoverflow.com/questions/55173115/reading-resource-files-in-python#comment97085457_55173115 specifically Michael Butscher's comment – Reedinationer Mar 15 '19 at 16:49

1 Answers1

0

You can use os.chdir() to change your directory before the import statement, and then to change it back afterward. This will allow you to specify the precise file to import. You can use os.listdir() to get the list of all files in the directory, and then simply index them. Using a loop will get all the modules in the folder, or providing the right index according to some pattern will give you a specific one. The glob module allows you to select files using regex.

import os

cwd = os.getcwd()

new_dir = 'project1/test/benchmark/'
list_dir = os.listdir(new_dir) # Find all matching

os.chdir(new_dir)
for i in range(len(list_dir)): # Import all of them (or index them in some way)
    module = list_dir[i][0:-3] # Filter off the '.py' file extension
    from module import *
os.chdir(cwd)

Alternatively, you can add the location to your path instead of changing directories. Take a look at this question for some additional resources.

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
Nathaniel
  • 3,230
  • 11
  • 18