Python中子文件夹中的.py文件引用父文件夹中的.py文件方法

文件夹结构描述

文件夹结构是这样的:

pythonWS2edCode
│
└───Chapter01
│   │   advanced_link_crawler.py
│   
└───Chapter02
    │   test_scrapers.py

现在文件test_scrapers.py中需要:

from Chapter01.advanced_link_crawler import download

也就是说,要导入父文件夹下的某个module。此时,我们在路径pythonWS2edCode运行:

python Chapter02/test_scrapers.py

或者在路径Chapter02下运行:

python test_scrapers.py

都将会得到如下:

Traceback (most recent call last):
File “test_scrapers.py”, line 6, in
from Chapter01.advanced_link_crawler import download
ModuleNotFoundError: No module named ‘Chapter01’

解决方法

正如博文解释的那样:

Starting from Python 3.3, implicit relative references are allowed no more. That means that the ability to reference a module in the parent directory is not possible and becomes a major limitation.
So in order to reference a module, the directory that contains a module must be present on PYTHONPATH – PYTHONPATH is an environment variable which contains the list of packages that will be loaded by Python upon execution. What is in PYTHONPATH is also present in sys.path as well.

于是,在test_scrapers.py文件的开头部分添加代码:

import os, sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

即可解决该问题。

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页