0

I would like to know how I can certain files based on generated variable names. An important note is that all the variables defined in those files, should also be accessible within the environment of my current script.

I've created a function, which should generate the names of the files that need to be imported in that specific case. Here's a simplified version of that function:

# the user provides these inputs: 
building_name = "cambridge"
room_name = "office1"


def determine_file_names(room=room_name, building=building_name):

    filename_building = "building_{}".format(building)    
    filename_room = "room_{}_{}".format(building, room)

    return(filename_building, filename_room)

building_file, room_file = determine_file_names()

# I'd like to import the files 'building_cambridge.py' and 'room_cambridge_office1.py' by doing the following: 
from Filefolder import building_file
from Filefolder import room_file 

The problem is that the required files are not imported. I receive an error that the file location of 'building_file.py' is not found:

Exception has occurred: ImportError
cannot import name 'building_file' from 'FileFolder' (unknown location)

It makes sense that it didn't find 'building_file.py', because I actually wanted python to import 'building_cambridge.py'.

I have about 300 files, of which only 2 specific ones need to be imported, so I have a dire need for a function like this to work. I have a strong preference for the import statement, as that allows me to use all content (such as variables) in those files directly in my current script, rather than that I have to create 100s of different classes in those files.

So again my question is: how can I ensure that I get to import the right files based on those generated variable names?

Lena
  • 133
  • 6
  • Have a look [here](https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path) (possible duplicate) – Tomerikoo Jun 18 '19 at 08:44
  • Possible duplicate of [How to import a module given its name?](https://stackoverflow.com/questions/301134/how-to-import-a-module-given-its-name) – Yury Tarabanko Jun 18 '19 at 08:44

0 Answers0