Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing multiple files named sequentially in Python

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?

like image 324
Manas Chaturvedi Avatar asked Dec 06 '25 01:12

Manas Chaturvedi


1 Answers

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)
like image 176
Mureinik Avatar answered Dec 08 '25 15:12

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!