4

In my code, I want to execute import filename for all the files that are present in a directory. I have a file abc.py under workspace. I am currently doing the following :

for filename in os.listdir(homedir/workspace) exec "import " + filename filename = eval(filename + '.function(variable)') 

The problem is that instead of doing import abc, it is doing import abc.py, and then showing the error no module named py

How can I resolve this?

Thanks in advance!

1
  • Note: you should avoid exec. You can achieve exactly the same effect with: module = __import__(filename). Using exec you are opening a security issue (e.g. someone can name a file os;os.sytem("killall cats") and when the code in your question executes all the cats will die! Using __import__ you would only receive an ImportError. Even better than __import__ is importlib.import_module, although it works in python2.7 and 3.1+ only. Commented May 9, 2014 at 13:17

3 Answers 3

8

You can use os.path.splitext

os.path.splitext(filename)[0] 

Of the returned two element array, the first element is just the filename, the second element is the extension. To be extra safe, you could double check that you did indeed grab a .py file:

if os.path.splitext(filename)[1] == '.py': # do stuff 
Sign up to request clarification or add additional context in comments.

Comments

1

To run .function(variable) for all Python files in a directory:

import os import sys from importlib import import_module dirpath = 'homedir/workspace' sys.path.append(dirpath) for filename in os.listdir(path) module_name, ext = os.path.splitext(filename) if ext == '.py': try: result = import_module(module_name).function(variable) except Exception as e: sys.stderr.write('error: %s: %s\n' % (filename, e)) continue else: print('%s: %s' % (filename, result)) 

See also Building a minimal plugin architecture in Python.

Comments

0

You can use glob:

import glob import os os.chdir("/mydir") for file in glob.glob("*.py"): # do something with file 

Read this to make sure You really want to use exec

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.