174

My python somehow can't find any modules in the same directory. What am I doing wrong? (python2.7)

So I have one directory '2014_07_13_test', with two files in it:

  1. test.py
  2. hello.py

where hello.py:

# !/usr/local/bin/python
# -*- coding: utf-8 -*-

def hello1():
    print 'HelloWorld!'

and test.py:

# !/usr/local/bin/python
# -*- coding: utf-8 -*-

from hello import hello1

hello1()

Still python gives me

>>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 4, in <module>
ImportError: No module named hello

What's wrong?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Philipp_Kats
  • 3,872
  • 3
  • 27
  • 44
  • 3
    How are you executing the script? Also what is the output of `import sys; sys.path` – Salem Jul 13 '14 at 11:39
  • 1
    Try `>>> import test` – martineau Jul 13 '14 at 11:42
  • @Casy_fill Do you run your program from the directory, where are the files present? For importing, it does not matter, that the importing and and imported files share a directory. Important is, that your Python interpreter has current directory set properly. – Jan Vlcinsky Jul 13 '14 at 11:52
  • Double check you're running the files from the expected root directory. – carloswm85 May 17 '21 at 13:48

16 Answers16

202

Change your import in test.py to:

from .hello import hello1
jfn
  • 2,486
  • 1
  • 13
  • 14
  • 32
    If anyone else finds this later, this is called relative imports and was added in python 2.5: https://docs.python.org/2.5/whatsnew/pep-328.html – sgfit May 12 '17 at 06:00
  • 27
    To import the whole module use `from . import hello` – ST7 Mar 29 '19 at 10:59
  • 24
    This simply doesn't work for me. I don't understand why Python imports are always such an incomprehensible nightmare. – Harry May 03 '22 at 06:42
  • 17
    This gives me `ImportError: attempted relative import with no known parent package` – Cameron Chandler Aug 19 '22 at 13:10
  • I get the same as @CameronChandler. I've tried adding a __init__.py to that folder, and removing it, and adding it to the PYTHONPATH and removing it, but to no avail. – Robert Rapplean Apr 13 '23 at 23:43
  • @CameronChandler are you doing this in a main file? Relative imports can not work in scripts with `__main__` – Litchy Aug 23 '23 at 05:33
116

Your code is fine, I suspect your problem is how you are launching it.

You need to launch python from your '2014_07_13_test' directory.

Open up a command prompt and 'cd' into your '2014_07_13_test' directory.

For instance:

$ cd /path/to/2014_07_13_test
$ python test.py

If you cannot 'cd' into the directory like this you can add it to sys.path

In test.py:

import sys, os
sys.path.append('/path/to/2014_07_13_test')

Or set/edit the PYTHONPATH

And all should be well...

...well there is a slight mistake with your 'shebang' lines (the first line in both your files), there shouldn't be a space between the '#' and the '!'

There is a better shebang you should use.

Also you don't need the shebang line on every file... only the ones you intend to run from your shell as executable files.

Community
  • 1
  • 1
Jeremy Allen
  • 6,434
  • 2
  • 26
  • 31
  • thanks a lot, that the issue! Unfortunately, SublimeRepl (which I use) don't support starting python from folder right now, so It seems I need to export PATH now – Philipp_Kats Jul 13 '14 at 12:17
  • 1
    Later readers please read till the bottom of the page to see other very useful answers, e.g. the one from jfn on _relative imports_. – HongboZhu Mar 03 '20 at 14:50
  • Yep, this was my problem. I had a big folder of Python practice projects open in VS Code and I was having big problems with finding things in the same directory. My problem was that, in the terminal, I hadn't changed directories to the sub-directory I had my current project in. Once I did that, problem solved. – Matt West Jul 05 '20 at 22:12
  • 2
    Note that sys.path.append() only adds the locations for the current python session and not permanently. – Amit Sharma Apr 12 '21 at 12:37
40

I had a similar problem, I solved it by explicitly adding the file's directory to the path list:

import os
import sys

file_dir = os.path.dirname(__file__)
sys.path.append(file_dir)

After that, I had no problem importing from the same directory.

ecotner
  • 507
  • 5
  • 5
37

Here is the generic solution I use. It solves the problem for importing from modules in the same folder:

import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

Put this at top of the module which gives the error "No module named xxxx"

apadana
  • 13,456
  • 15
  • 82
  • 98
  • 1
    This helped me load module from parent directory, by replacing ".." with "../..". Thanks a lot! – Nikola R. Jan 09 '19 at 08:05
  • 1
    is __file__ name of file to be imported or current module where we are importing module or it is constant – Manoj Nov 22 '19 at 16:23
14

In my case, Python was unable to find it because I'd put the code inside a module with hyphens, e.g. my-module. When I changed it to my_module it worked.

Chris Claxton
  • 413
  • 6
  • 11
2

I ran into this issue. I had three folders in the same directory so I had to specify which folder. Ex: from Folder import script

Nippon87
  • 81
  • 1
  • 6
2

I had somewhat of a similar problem. I could not import modules even though they all were in the same directory (importError). I tried out the solutions above but none of them worked for me. I had to set up the path myself (manually). Also, the code was run on my university server, perhaps that's why I had to set the path manually.

import sys
sys.path.append(r'path_to_directory_where_all_modules_are')

I recommend reading The Module Search Path

1

The following doesn't solve the OP's problem, but the title and error is exactly what I faced.

If your project has a setup.py script in it, you can install that package you are in, with python3 -m pip install -e . or python3 setup.py install or python3 setup.py develop, and this package will be installed, but still editable (so changes to the code will be seen when importing the package). If it doesn't have a setup.py, make sense of it.

Anyway, the problem OP faces seems to not exist anymore?

file one.py:

def function():
    print("output")

file two.py:

#!/usr/bin/env python3

import one
one.function()
chmod +x two.py # To allow execution of the python file
./two.py # Only works if you have a python shebang

Command line output: output

Other solutions seem 'dirty'

In the case of OP with 2 test files, modifying them to work is probably fine. However, in other real scenarios, the methods listed in the other answers is probably not recommended. They require you to modify the python code or restrict your flexibility (running the python file from a specific directory) and generally introduce annoyances. What if you've just cloned a project, and this happens? It probably already works for other people, and making code changes is unnecessary. The chosen answer also wants people to run a script from a specific folder to make it work. This can be a source of long term annoyance, which is never good. It also suggests adding your specific python folder to PATH (can be done through python or command line). Again, what happens if you rename or move the folder in a few months? You have to hunt down this page again, and eventually discover you need to set the path (and that you did exactly this a few months ago), and that you simply need to update a path (sure you could use sys.path and programmatically set it, but this can be flaky still). Many sources of great annoyance.

Ben Butterworth
  • 22,056
  • 10
  • 114
  • 167
1

If you are sure that all the modules, files you're trying to import are in the same folder and they should be picked directly just by giving the name and not the reference path then your editor or terminal should have opened the main folder where all the files/modules are present.

Either, try running from Terminal, make sure first you go to the correct directory.

cd path to the root folder where all the modules are

python script.py

Or if running [F5] from the editor i.e VsCode then open the complete folder there and not the individual files.

Iqra.
  • 685
  • 1
  • 7
  • 18
1

After spending hours to get imports working like:

from business import Business
from .business import Business
import .Business
import business.Business

... I got finally rid of my embedded python installation and installed python from the scratch by be the .exe file for all users like in

c:\Program Files\Python310

then I made sure my PATH Variable is up to date with the new installation (so what we want to see or make are entries like c:\Program Files\Python310 and c:\Program Files\Python310\Scripts and %USERPROFILE%\AppData\Roaming\Python\Python310\Scripts) and started a cmd with administrator privileges, downloaded the get-pip.py file and run it in the elivated cmd like python get-pip.py and finaly everything worked as expected... I don't know why or what I did wrong or so, but python really seems that it need to be integrated deeply into windows or it just do not work the easy way. It doesn't happen too often, but in this case it worked a lot better in linux ;)

1

The imports only worked for me when I recreated a new file using the command line instead of Visual Studio Code's "Create New File" command.

In the command line:

touch your_file.py

then, import as per the other's recommendation

from your_file import your_function
ryanlhy
  • 11
  • 3
0

Also recheck spelling of both the file and the module for typos.

For example

import passwords

When the file name has been saved as password missing an s.

It might sound obvious but it can sometimes be something as simple as this when all other advice above not working :)

Christopher
  • 427
  • 1
  • 8
  • 18
0

This kind of problems happens when your project path is changed. You need to use:

cd path\to\the\files_path

simply

Arij Aladel
  • 356
  • 1
  • 3
  • 10
0

I just ran into this. I have a flask app that starts in an app.py file. I had lots of other files scattered around in the same directory when I decided that I wanted to clean it up a bit so I created a sub-directory called "local_lib" and moved all of the .py files except for app.py into it. Then I changed the import lines in app.py to look like this...

from local_lib.user import User

But I couldn't seem to import files into each other inside the local_lib directory. My directory structure looks like this...

/
  - app.py
  - local_lib/
     - users.py
     - app_config.py
     - data_ops.py
     - db_connect.py
     - forms.py
     - logger.py
     - search_dao.py

It eventually dawned on me that the application was running in the context of the directory where app.py lives so I had to change my imports to ALL look like this...

from local_lib import search_dao
from local_lib import app_config as cfg
from local_lib.user import User
from local_lib import logger

which ficksed it. PyCharm doesn't like it, because it has all of the imports underline din red wavy lines, but it works.

I'm still learning Python so this is annoying, but it is what it is.

0

It is likely that your working directory is still set to the parent folder. To solve this issue, you need to first check your current working directory as follows:

import os
print(os.getcwd())

If it's different from the directory containing the modules set your correct directory as follows:

os.chdir(os.getcwd()+'/correct_project_folder')
-1

The same error, but I didn't find an answer to my case, maybe someone need my solution.

It appears that in PyCharm I've created .py file, but somehow in windows directory of my project file was blank and without .py. So I rename extension right in derictory and it worked.

Picture before changing an extension

Sofi
  • 31
  • 4
  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/33080062) – chrslg Nov 06 '22 at 14:34