You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不违反PEP-8规范的情况下从其他目录导入文件?

Fixing the "Unable to import 'DictsOrganizations'" Error (PEP8-Compliant)

Got it, let's work through this import problem. You've already marked DictsOrganizations as a Python package by adding __init__.py, but still can't import it without breaking PEP8 (since sys.path.append would need to sit in the middle of your imports). Here are clean, standard solutions that follow PEP8 rules:

1. Run your script with the -m flag

If your current script and the DictsOrganizations package live in the same project root directory, running your script with Python's module flag will automatically add the project root to your sys.path—no messy path hacks needed.

For example, if your script is named main.py, navigate to your project root in the terminal and run:

python -m main

Then you can use the clean, standard import at the top of your file:

from DictsOrganizations import BalancedTree

2. Turn your project into an installable package

This is the most robust long-term fix, especially for larger projects. Create a setup.py (or pyproject.toml for modern Python) in your project root to define your package structure.

Example setup.py:

from setuptools import setup, find_packages

setup(
    name="your-project-name",
    version="0.1.0",
    packages=find_packages(),
)

Then install your project in editable mode (so changes to your code take effect immediately) by running this from the project root:

pip install -e .

Now Python will recognize DictsOrganizations as a globally available package, and you can import it normally in any file in your project.

3. Use relative imports (if your script is part of a package hierarchy)

If your current script is inside another subpackage (not just a standalone file), you can use relative imports to reference DictsOrganizations.

For example, if your project structure looks like this:

project-root/
├── DictsOrganizations/
│   ├── __init__.py
│   └── BalancedTree.py
└── my_subpackage/
    ├── __init__.py
    └── your_script.py

In your_script.py, you can write:

from ..DictsOrganizations import BalancedTree

Note: Relative imports only work when running the script as part of a package. So you'd run it from the project root with:

python -m my_subpackage.your_script

Why your initial setup didn't work

Even with __init__.py, Python can't find DictsOrganizations because the directory containing it isn't in sys.path. sys.path.append would fix this, but PEP8 requires all import statements to be at the top of your file—inserting a path modification in the middle of your imports violates that rule. The solutions above avoid that by ensuring Python can find your package natively.

内容的提问来源于stack exchange,提问作者CFmoto6615

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:33:05