Python tidak dapat menemukan modul di folder yang sama


98

Python saya entah bagaimana tidak dapat menemukan modul apa pun di direktori yang sama. Apa yang saya lakukan salah? (python2.7)

Jadi saya memiliki satu direktori '2014_07_13_test', dengan dua file di dalamnya:

  1. test.py
  2. halo

dimana hello.py:

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

def hello1():
    print 'HelloWorld!'

dan test.py:

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

from hello import hello1

hello1()

Masih python memberi saya

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

Apa yang salah?


2
Bagaimana Anda menjalankan skrip? Juga apa output dariimport sys; sys.path
Salem

1
Coba>>> import test
martineau

@Casy_fill Apakah Anda menjalankan program dari direktori, di mana file berada? Untuk mengimpor, tidak masalah, bahwa file yang diimpor dan dan diimpor berbagi direktori. Yang penting, interpreter Python Anda memiliki direktori saat ini yang disetel dengan benar.
Jan Vlcinsky

Jawaban:


81

Kode Anda baik-baik saja, saya rasa masalah Anda adalah bagaimana Anda meluncurkannya.

Anda perlu meluncurkan python dari direktori '2014_07_13_test' Anda.

Buka prompt perintah dan 'cd' ke direktori '2014_07_13_test' Anda.

Contohnya:

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

Jika Anda tidak dapat 'cd' ke direktori seperti ini, Anda dapat menambahkannya ke sys.path

Di 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.


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

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

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

105

Change your import in test.py to:

from .hello import hello1

23
If anyone else finds this later, this is called relative imports and was added in python 2.5: docs.python.org/2.5/whatsnew/pep-328.html
sgfit

9
To import the whole module use from . import hello
ST7

I think this is a better solution than the best accepted answer. I use the whole module import, as ST7 pointed out: from . import local_module
Gene M

25

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.


2
While this worked, the answer from jwn using relative imports was a much cleaner solution.
Russ Schultz

16

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"


1
This helped me load module from parent directory, by replacing ".." with "../..". Thanks a lot!
Nikola R.

1
is file name of file to be imported or current module where we are importing module or it is constant
Manoj

9

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.


1

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


0

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.


0

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.

Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.