importing a module from a file without the '.py' suffix

Rob Cliffe rob.cliffe at
Fri Oct 22 08:00:54 EDT 2021

As far as I know, it can't be done.
If I was REALLY desperate I might try (tested)

import os
os.rename('myfile.myext', '')
import myfile
os.rename('', 'myfile.myext')
# with appropriate modifications if myfile is not in the current directory

but this is a horrible solution, subject to race conditions, file 
permission errors, wrong state after a crash, and probably other problems.
It could be cleaned up a bit with try ... except, but is still not to be 

Can you just create a copy of your file with a .py extension?
Best wishes
Rob Cliffe

On 22/10/2021 12:19, Antoon Pardon wrote:
> I have a file with python code but the name doesn't end with the '.py' 
> suffix.
> What is the easiest way to import this code as a module without 
> changing its name?

More information about the Python-list mailing list