Technology

How to import all the files from a directory using Python

python-logo

 

 

 

STEP 1 : Execute the following command in the folder from which you need to import files from:

$ touch __init__.py

Or simply create a blank file __init__.py in the folder.

STEP2 : Prepare your __init__.py. The idea is to enable __init__ to know about all the files of your directory.

Paste the following code in __init__.py

import os
modules = []
file_list = os.listdir(os.path.dirname(__file__))
for files in file_list:
    mod_name, file_ext = os.path.splitext(os.path.split(files)[-1])
    if file_ext.lower() == ‘.py’:
        if mod_name != ‘__init__’:
            modules.append(files.split(“.”)[0])

__all__ = modules

STEP 3:  Import in the desired file present on some other location

Include the following code on top your file:

import os
dir_name = ‘foo.bar’
file_list = os.listdir(dir_name)
for files in file_list:
    mod_name, file_ext = os.path.splitext(os.path.split(files)[-1])
    if file_ext.lower() == ‘.py’ and  mod_name != ‘__init__’:
        exec “from {0} import {1}”.format(dir_name + files.split(“.”)[0], files.split(“.”)[0])

Advertisements

One thought on “How to import all the files from a directory using Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s