python – How to import a function from a module in the same folder?

python – How to import a function from a module in the same folder?

You need to add __init__.py in your core folder. You getting this error because python does not recognise your folder as python package

After that do

from .posts_run import get_all_posts
#    ^ here do relative import
# or
from core.posts_run import get_all_posts
# because your package named core and importing looks in root folder

MyFile.py:

def myfunc():
    return 12

start python interpreter:

>>> from MyFile import myFunc
>>> myFunc()
12

Alternatively:

>>> import MyFile
>>> MyFile.myFunc()
12

Does this not work on your machine?

python – How to import a function from a module in the same folder?

A cheat solution can be found from this question (question is Why use sys.path.append(path) instead of sys.path.insert(1, path)? ). Essentially you do the following

    import sys
    sys.path.insert(1, directory_path_your_code_is_in)
    import file_name_without_dot_py_at_end

This will get round that as you are running it in PyCharm 2016.1, it might be in a different current directory to what you are expecting…

Leave a Reply

Your email address will not be published. Required fields are marked *