Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to import data from another .py file, if the file path is stored in a variable?

I am writing a program to help me build matrixs for my pygame projects. (I am using tkinter for the setup window, then pygame to colour tiles to give them values between 0 and 9)

I was hoping that I could save projects with named files, to later be reopened. All I need is the values of the variables store in my .py save files. I’ve had no problem creating these save files, however I am struggling to load these files.

Currently I am using tkinters ‘file dialog’ to get the file address, then using the os module to get the filename from the address and assigning that to a variable.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem I am having is importing the information from a file when the filename could vary and is therefore stored in a variable.

Can anyone point me in the right direction to be able to import without having the filename when writing the code? TIA

Not my actual program, just put together the simplest example of the problem I’m trying to fix (File2 just contains "var = 1")

second_file = "file2.py"

from second_file import *

print(var)

Running this obviously gives me "ModuleNotFoundError: No module named ‘second_file’"
Just wondering if there is a way to rewrite this so it knows it’s a variable?

>Solution :

If you want to import a module using a variable name in Python, you can use the importlib module’s import_module function. This allows you to dynamically import a module using a string (variable) that contains the module’s name. Here’s how you can rewrite your code to achieve this:

import importlib

second_file = "file2" # Note that you don’t need the ‘.py’ extension

module = importlib.import_module(second_file)
print(module.var)

importlib.import_module(second_file) imports the module specified by the value of the second_file variable. Then you can access the variable var using module.var.

Ensure that the second_file variable contains the module name you want to import, without the .py extension. The module should be located in the same directory as the script importing it or available in the Python path.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading