Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove .py extension while using os.listdir

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!

like image 406
Kat.S Avatar asked Feb 14 '23 00:02

Kat.S


1 Answers

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
like image 69
Cory Kramer Avatar answered Feb 26 '23 11:02

Cory Kramer