Python 3.6同目录模块导入报错:无法导入second_file的解决办法
Alright, let's break down why those import attempts are failing and fix this step by step.
问题根源
When you run first_file.py directly (like python first_file.py), Python treats it as the main module (__name__ == '__main__'). Relative imports (like from . import ...) don't work in this scenario—they're designed exclusively for modules that are part of a proper Python package.
As for from dir import second_file, that fails for one of two reasons:
- Your working directory isn't the parent folder of
dir, so Python can't locate thedirpackage. - The
dirfolder isn't marked as a Python package (missing an__init__.pyfile, which is still critical for compatibility in Python 3.6).
解决方案1:把dir变成包,从父目录运行(推荐)
This is the cleanest, most Pythonic approach for intra-package imports:
- Add an empty
__init__.pyfile to thedirfolder—this tells Python thatdiris a valid package. - Navigate to the parent folder of
dir(the folder that containsdiritself). - Run your script using Python's module syntax:
python -m dir.first_file - Now inside
first_file.py, you can use the relative import successfully:from . import second_file
解决方案2:临时修改sys.path(应急用,不推荐长期使用)
If you need to run first_file.py directly without adjusting your workflow, you can manually add the script's directory to Python's module search path. Add this code at the very top of first_file.py:
import sys from pathlib import Path # Add the current script's directory to Python's search path sys.path.append(str(Path(__file__).parent))
Then you can import second_file directly:
import second_file # Or if you prefer: from dir import second_file (if dir is already in sys.path)
Note: This method can trigger naming conflicts if other modules share the same name, so stick to Solution 1 whenever possible.
内容的提问来源于stack exchange,提问作者Sri Divya




