如何在python中从父目录导入文件

问题描述 投票:0回答:2

我目前有以下文件夹结构

mypy
    > test_fldr
        > test.py
    
    > user_funcs.py

我的目标是能够通过在 test.py 文件中编写 import 语句来访问和利用 user_funcs.py 文件中的函数。

我尝试使用如下的相对导入

from .. import user_funcs

但这只会出现这样的错误

ImportError: attempted relative import with no known parent package

我也尝试过通过像这样引用父级来导入库

from mypy import user_funcs

但这只给了我以下错误

ImportError: cannot import name 'user_funcs' from 'mypy' (C:\Users\joest\AppData\Local\Programs\Python\Python311\Lib\site-packages\mypy\__init__.cp311-win_amd64.pyd)

是否有任何干净的解决方案不需要使用 sys.path 或类似于以下内容的任何内容,因为我的代码编辑器会自动格式化代码,因此所有导入都位于顶部,这使得 Thingg 无法工作并且可能非常烦人没过多久

import sys
# example: sys.path(...)
import user_funcs

谢谢:)

python directory subdirectory
2个回答
0
投票

在 Python 中,所有导入路径都相对于解释器运行的目录,因此为了让您的

test.py
能够访问父目录中的
user_funcs.py
,您通常应该
test.py
import
user_funcs

import user_funcs

并从

test.py
所在位置(即从
user_funcs.py
目录)运行
mypy

mypy> python test_fldr/test.py

0
投票

尝试使用

import user_funcs.py

如果
user_funcs
位于名为
funcs
的目录中 那么你会做
from funcs import user_funcs.py

© www.soinside.com 2019 - 2024. All rights reserved.