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.

Índice
  1. Using importlib
  2. Using __import__()
  3. Conclusion

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.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information