How to import python file from folder as folder.file using "from" keyword?

I had a file at db/ I moved the file and now the path is project/db/
Previously I imported that file using this syntax:

import db.connection

And somewhere in the code I had access to the file:


Since now the file is moved, I know only two options to import the file: using import and from import keywords. But both of them will change the reference to the file. I’ll show you what I mean.
If I use import:

import project.db.connection

Then the new reference is project.db.connection and I need to change the code that accesses the file as well, so that it becomes:


If I use from import:

from project.db import connection

The same problem, but now the reference is connection.

I thought I could do that:

from project import db.connection

But python gives me an error at that line of code:

from project import db.connection

SyntaxError: invalid syntax

So if it’s possible, how to import the new file having the reference db.connection, so I don’t need to change the code that accesses that file?

Depending on how the module is set up, you may simply be able to do this:

from project import db

But if that doesn’t work (if db.connection raises AttributeError), it can be done in two steps:

import project.db.connection # force it to be loaded
from project import db

The first line needs only be done once for the session, and one elegant way to manage it is to do that import inside project/ or project/db/ - after that, the simple one-line version will do what you want.