将包含XLRD模块的文件导入其他Python文件



我一直在尝试将此 test.py 文件导入另一个python文件,但没有成功。

import xlrd
import term
import perpetuity
loc = "C:PycharmProjects/Life annuities/tables.xlsx"   # this is the file location.
wb = xlrd.open_workbook(loc)

def tables_advance_perpetuity():
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
num = int(input('enter the age of the life:'))
for i in range(sheet.nrows):
x = sheet.cell_value(i, 0)
if x == num:
dx = sheet.cell_value(num - 1, 2)
nx = sheet.cell_value(num - 1, 6)
print(dx)
print(nx)
ann = nx / dx
print(f'Annuity value is {ann}')

尝试将 test.py 文件导入此 python 文件 (interface.py( 时,程序将运行并退出而不导入 test.py 文件。但是,我已经能够成功导入 term.py 和 perpetuity.py 文件

import perpetuity
import term
import test

print('Annuity options are :')
print('t 1. Term annuities')
print('t 2. perpetuities')
print('t 3. deferred annuities')
print('=' * 50)
option = int(input('pick one that you want to compute: '))
print('=' * 50)
if option == 1:
toption = int(input('t1. Payable in Advance:n'
't2. Payable in Arrears:n'
't3. Payable continously:n'))
print('=' * 50)
if toption == 1:
term.Term_advance()
if toption == 2:
term.Term_arrears()
if toption == 3:
term.Term_continously()
basis = input('what is the calculation basis::n'
'1.t AM 92n'
'2.t ELT 15 MALESn')
if basis == 1:
test.tables_advance_term()
print('end')

代码不会导入您的test.py文件,因为它会导入内置的 pythontest包。请注意,包优先于同名模块。

如下所示,我能够成功地从本机pythontest包中导入support模块。

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> from test import support
>>> 

要解决此问题,只需将test.py文件名更改为与内置 python 库/包不冲突的名称。

参考: https://docs.python.org/3/library/test.html

最新更新