I have about 50 Python files in a directory, all named in a sequential order, for example: myfile1, myfile2.....myfile50. Now, I want to import the contents of these files inside another Python file. This is what I tried:
i = 0
while i < 51:
file_name = 'myfile' + i
import file_name
i += 1
However, I get the following error:
ImportError: No module named file_name
How may I import all these sequentially named files inside another Python file, without having to write import for each file individually?
You can't use import to import modules from a string containing their name. You could, however, use importlib:
import importlib
i = 0
while i < 51:
file_name = 'myfile' + str(i)
importlib.import_module(file_name)
i += 1
Also, note that the "pythonic" way of iterating a set number of times would be to use a for loop:
for i in range(0, 51):
file_name = 'myfile' + str(i)
importlib.import_module(file_name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With