How to import filename starting with a number in Python?
When working with Python, sometimes we encounter filenames that begin with a number, which can cause issues when trying to import them using the regular import statement. However, there is a simple solution to this problem.
Using importlib
The importlib
module provides a function called import_module()
that allows us to import modules with arbitrary names, including those that begin with a number.
<!-- language: python -->
import importlib
module_name = "123example_module"
module = importlib.import_module(module_name)
Here, we first import the importlib
module and then specify the name of the module we want to import, even though it begins with a number. We then use the import_module()
function to import the module.
Using __import__()
Another way to import modules with names starting with a number is to use the built-in function __import__()
.
<!-- language: python -->
module_name = "123example_module"
module = __import__(module_name)
Here, we simply specify the name of the module we want to import and use the __import__()
function to import it.
Conclusion
Importing modules with names starting with a number is easy in Python, thanks to the importlib
module and the __import__()
function. With these tools, we can import any module regardless of its name.
Leave a Reply
Related posts