简体   繁体   中英

How to import python module from different directory, same level, but different folder

I have a directory structure like

Documents/
    Project_1/
        module_1.py
    Project_2/
        module_2.py

If I want to import module_1.py into module_2.py, what is the syntax for it?

I have tried variations on

import ../Project_1/module_1

And

from .Project_1 import module_1

But I can't get it to work and have only done this once before in another project.

You have two alternatives;

from Documents.project_1 import module1.py

or

import Documents.project_1.module1.py

It is a crude solution, but I ended up with something like this:

#This thing modifies the path
from sys import path

#This gets our user directory
from os import environ

#add module_1's location to path
path.append(environ['USERPROFILE'] + "\\Documents\\Project_1")

#import it now
import module_1

This is not the most elegant solution, but it can work on almost any Windows machine, assuming the folders are placed in their Documents.

The code about Environ could be reasonably replaced to match another directory, though.

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