0

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.

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?

  • One way is to read the file as text and feed it to `exec`. Generally, `exec` is not safe but not less safe than directly importing the file. – Michael Butscher Aug 02 '23 at 16:21
  • Check the `importlib` module and see if something in there helps. – Mark Ransom Aug 02 '23 at 16:22
  • 2
    You could use `importlib.import_module()`, but if that file only contains key-value pairs then consider storing it as .json or .ini instead. – DallogFheir Aug 02 '23 at 16:22
  • Does this answer your question? [How can I import a module dynamically given the full path?](https://stackoverflow.com/questions/67631/how-can-i-import-a-module-dynamically-given-the-full-path) – Jonathan Feenstra Aug 02 '23 at 16:38
  • I have also tried 'importlib.import_module(second_file)' this gives me 'ModuleNotFoundError: No module named 'file2'' . So it's definitely reading it as a variable, however it says it's not a module, I have also tried the same thing with a json file. I am still very new to this so forgive me if I'm being stupid haha – Jordan Beauchamp Aug 02 '23 at 16:42

2 Answers2

1

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.

finceth
  • 26
  • 2
  • Ok I was being a bit stupid! Thank you! This is great! I want the save file to replace some of the variables I have set previously, is there a better way of doing that than 'var = module.var' ? – Jordan Beauchamp Aug 02 '23 at 16:57
  • I’m not sure what you mean, can you elaborate or give an example? – finceth Aug 03 '23 at 15:29
0

Yes, it is possible. Python provides several ways to achieve this, and one common approach is by using the importlib module https://docs.python.org/3/library/importlib.html

For Example:

## file2.py

example_var = "You're in file2"
## main.py

import importlib.util

# Store the file path in a variable
second_file = 'file2.py'

# Create a module specification from the file path
spec = importlib.util.spec_from_file_location('data', second_file)

# Create a new module based on the specification
data_module = importlib.util.module_from_spec(spec)

# Execute the module (run the code in the .py file)
spec.loader.exec_module(data_module)

# Access the data from the imported module
data = data_module.example_var
print(data)  # Output: You're in file2

Good Luck

Just a thought: please learn how to create python packages, and learn about class in python the create much cleaner code. Also, functional programming can be very useful in these cases. The above code can be created without the use of importlib module.