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)

即可解决该问题。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值