Python ImportError:无法导入名称__init__.py

时间:2019-02-22 20:02:33

标签: python import

我收到此错误:

ImportError: cannot import name 'life_table' from 'cdc_life_tables' (C:\Users\tony\OneDrive\Documents\Retirement\retirement-mc-master\cdc_life_tables\__init__.py)

当我尝试运行此代码(retirement_mc.py)时:

from cdc_life_tables import life_table

init .py看起来像这样

#!/usr/bin/env python
from cdc_life_tables import *

和cdc_life_tables.py包含life_table,如下所示:

def life_table(state_abbrev, demographic_group):

    state_abbrev = state_abbrev.upper()

    try:
        state = abbrev2name[state_abbrev]
    except KeyError:
        raise ValueError('"{}" not a state abbreviation.'.format(state_abbrev))

    state = state.lower().replace(' ', '_')


    try:
        demographic_group = demographic_group.lower()
        if len(demographic_group) > 2:
           demographic_group = groups_long2short[demographic_group]
    except KeyError:
        raise ValueError('"{}" not a valid .'.format(demographic_group))

    s = '{}{}_{}.csv'.format(lt_dir, state, demographic_group)

    if os.path.exists(s):
        df = pd.read_csv(s)
    else:
        raise ValueError('{} not a demographic group for {}.'.format(demographic_group, state_abbrev))

    return df['qx']

if __name__ == '__main__':
    q = life_table('PA', 'wf')

我正在使用Spyder(Python 3.7)

1 个答案:

答案 0 :(得分:1)

此行:

from cdc_life_tables import *

您的软件包正在尝试从本身进行import *。您需要从当前程序包的import * 子模块cdc_life_tables,最容易的是相对导入:

from .cdc_life_tables import *