简体   繁体   中英

ModuleNotFoundError when trying to import file from one folder into another file located in another directory

I working with a group on a project that is being used with Git and Github. I have a local main project folder that contains two sub-directories(ie Utilities and Testing). However, in order to run the test files inside the directory project/Testing, I need to import files from the Utilities directory itself. I am familiar with some python techniques of importing for example: from. import or from import * or import. However, as I am trying to use these techniques in my testing.py file located in my testing folder, I run into a moduleNotFoundError: No modules named "Utilities" and currently both directories contain an init .py file.

我的层次结构的直观表示

I tried doing something like this...

from Utilities.deck import Deck and from Utilities import * however both seems to not be working. I came across adding the init .py file inside both directories, and thus the init file for Utilities contains the following...

from .card import *
from .deck import *
from .player import *

However that did not work either. I am not really sure what else to do to solve this issue and could really use some help and guidance that will work for me and my team to avoid this issue in the near future.

Append parent path by adding this line before the imports in the files in Testing:

import path
import sys
 
# directory reach
directory = path.Path(__file__).abspath()
 
# setting path
sys.path.append(directory.parent.parent)

Then this import should work:

from Utilities.deck import Deck

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