安装finance包后导入bankdate模块失败,如何直接导入.py文件?
Hey there, let's work through your problems step by step:
ImportError: No module named 'bankdate' Since you’ve confirmed bankdate.py exists in the finance folder and the __init__.py depends on it, here are the most likely fixes to resolve the error:
Fix relative imports in
__init__.py
Python 3 dropped support for implicit relative imports. If yourfinance/__init__.pyuses a line likeimport bankdate, update it to use explicit relative import syntax:from . import bankdate # Tells Python to look for bankdate in the same directory as __init__.pyThis ensures Python correctly locates the module within the
financepackage structure.Verify the installation integrity
Run this command to check where thefinancepackage was installed:pip show financeNavigate to the
Locationpath listed, then confirm the installedfinancefolder contains both__init__.pyandbankdate.py. If files are missing, uninstall the package first withpip uninstall finance, then reinstall usingpip install .from the extracted package directory—this method is more reliable thanpython setup.py installfor modern Python versions.Check for naming conflicts
Make sure you don’t have a file namedfinance.pyorbankdate.pyin your current working directory. Such files would override the installed package and trigger the import error.
If you need to import a standalone .py file (not part of an installed package), here are a few straightforward methods:
Add the file’s directory to Python’s search path
Temporarily add the folder containing your.pyfile tosys.path(Python’s module lookup list):import sys sys.path.append("/full/path/to/the/folder/holding/your/file") import bankdate # Python can now locate the fileLoad the file directly with
importlib
For more control, useimportlib.machinery.SourceFileLoaderto load the file explicitly:from importlib.machinery import SourceFileLoader # Load the module (first argument is the name you want to reference it by) bankdate = SourceFileLoader("bankdate", "/full/path/to/bankdate.py").load_module()Use relative imports (for project-local files)
If the.pyfile is in a subdirectory of your current script (and your project has an__init__.pyto mark it as a package), use relative import syntax:from .finance import bankdate # Works if bankdate.py is in a 'finance' subfolder
内容的提问来源于stack exchange,提问作者Hannah Lee

