简体   繁体   中英

How do i import a function from a file in a parent directory

I have a pycharm project with one python file called main.py

on my desktop i have a folder called 'Python' inside it looks like this:

 - Desktop
    - framework.py
    - Python
        - Python Projects
            - Project File
                - main.py

In my main file i want to import a function from the framework file. for example if my framework file looks like this:

def print_hi():
    print("hi")

how would i import the function into my main file?

  1. Use sys module and set the path directly to the required module.
sys.path.append('add_path_here') 
  1. use sys module as well as the path module for getting the directory and set the path directly to the required module

Example,

directory = path.path(__file__).abspath()
sys.path.append(directory.parent.parent)

in the python structure for import, you should use system layout I mean:

parent/
    __init__.py
    one/
        __init__.py
    two/
        __init__.py
    three/
        __init__.py

so first of all use init file the simply use import

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM