Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get Python to import from a different folder

Tags:

python

I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:

Server     -server.py     -Models         --user.py 

Here's the contents of server.py:

from sys import path from os import getcwd path.append(getcwd() + "\\models") #Yes, i'm on windows print path import user  u=user.User() #error on this line 

And user.py:

class User(Entity):     using_options(tablename='users')      username = Field(String(15))     password = Field(String(64))     email    = Field(String(50))     status   = Field(Integer)     created  = Field(DateTime) 

The error is: AttributeError: 'module' object has no attribute 'User'

like image 419
ryeguy Avatar asked Jan 19 '09 03:01

ryeguy


People also ask

Can't import from another folder Python?

You need to add Python path runtime using the sys. path. append() method will then resolve the importing file's path. Importing files from one folder to another in Python is a tricky task, and by default, you can't do that, and if you try, you will get an error.

How can we import .py file from another directory?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.

Can import module from another folder Python?

The most Pythonic way to import a module from another folder is to place an empty file named __init__.py into that folder and use the relative path with the dot notation. For example, a module in the parent folder would be imported with from .. import module .

How do you set a path to import in Python?

The easiest way to import a Python module, given the full path is to add the path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.


2 Answers

I believe you need to create a file called __init__.py in the Models directory so that python treats it as a module.

Then you can do:

from Models.user import User 

You can include code in the __init__.py (for instance initialization code that a few different classes need) or leave it blank. But it must be there.

like image 128
Dana Avatar answered Sep 22 '22 01:09

Dana


You have to create __init__.py on the Models subfolder. The file may be empty. It defines a package.

Then you can do:

from Models.user import User 

Read all about it in python tutorial, here.

There is also a good article about file organization of python projects here.

like image 25
nosklo Avatar answered Sep 19 '22 01:09

nosklo