You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python 3.6同目录模块导入报错:无法导入second_file的解决办法

解决同一目录下Python模块导入错误(Python 3.6)

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 the dir package.
  • The dir folder isn't marked as a Python package (missing an __init__.py file, which is still critical for compatibility in Python 3.6).

解决方案1:把dir变成包,从父目录运行(推荐)

This is the cleanest, most Pythonic approach for intra-package imports:

  1. Add an empty __init__.py file to the dir folder—this tells Python that dir is a valid package.
  2. Navigate to the parent folder of dir (the folder that contains dir itself).
  3. Run your script using Python's module syntax:
    python -m dir.first_file
    
  4. 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

火山引擎 最新活动