从子目录导入文件?

发布于 2024-08-01 17:32:06 字数 861 浏览 8 评论 0原文

我有一个名为 tester.py 的文件,位于 /project 上。

/project 有一个名为 lib 的子目录,其中有一个名为 BoxTime.py 的文件:

/project/tester.py
/project/lib/BoxTime.py

我想从以下位置导入 BoxTime 测试员。 我已经尝试过:

import lib.BoxTime

结果是:

Traceback (most recent call last):
  File "./tester.py", line 3, in <module>
    import lib.BoxTime
ImportError: No module named lib.BoxTime

有什么想法如何从子目录导入 BoxTime 吗?

编辑

__init__.py 是问题所在,但不要忘记将 BoxTime 引用为 lib.BoxTime ,或使用:

import lib.BoxTime as BT
...
BT.bt_function()

I have a file called tester.py, located on /project.

/project has a subdirectory called lib, with a file called BoxTime.py:

/project/tester.py
/project/lib/BoxTime.py

I want to import BoxTime from tester. I have tried this:

import lib.BoxTime

Which resulted:

Traceback (most recent call last):
  File "./tester.py", line 3, in <module>
    import lib.BoxTime
ImportError: No module named lib.BoxTime

Any ideas how to import BoxTime from the subdirectory?

EDIT

The __init__.py was the problem, but don't forget to refer to BoxTime as lib.BoxTime, or use:

import lib.BoxTime as BT
...
BT.bt_function()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

旧街凉风 2024-08-08 17:32:06

查看包文档(第 6.4 节)< /强>。

简而言之,您需要

__init__.py

lib目录中放置一个名为的空白文件。

Take a look at the Packages documentation (Section 6.4).

In short, you need to put a blank file named

__init__.py

in the lib directory.

独﹏钓一江月 2024-08-08 17:32:06
  • 创建一个名为 lib 的子目录。
  • 创建一个名为 lib\__init__.py 的空文件。
  • lib\BoxTime.py中,编写一个函数foo(),如下所示:

    def foo(): 
          打印“富!” 
      
  • 在上面目录中的客户端代码中 <代码>lib,写入:

    从 lib 导入 BoxTime 
      BoxTime.foo() 
      
  • 运行客户端代码。 您将得到:

    <前><代码>富!


很久以后——在 Linux 中,它看起来像这样:

% cd ~/tmp
% mkdir lib
% touch lib/__init__.py
% cat > lib/BoxTime.py << EOF
heredoc> def foo():
heredoc>     print "foo!"
heredoc> EOF
% tree lib
lib
├── BoxTime.py
└── __init__.py

0 directories, 2 files
% python 
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib import BoxTime
>>> BoxTime.foo()
foo!
  • Create a subdirectory named lib.
  • Create an empty file named lib\__init__.py.
  • In lib\BoxTime.py, write a function foo() like this:

    def foo():
        print "foo!"
    
  • In your client code in the directory above lib, write:

    from lib import BoxTime
    BoxTime.foo()
    
  • Run your client code. You will get:

    foo!
    

Much later -- in linux, it would look like this:

% cd ~/tmp
% mkdir lib
% touch lib/__init__.py
% cat > lib/BoxTime.py << EOF
heredoc> def foo():
heredoc>     print "foo!"
heredoc> EOF
% tree lib
lib
├── BoxTime.py
└── __init__.py

0 directories, 2 files
% python 
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib import BoxTime
>>> BoxTime.foo()
foo!
何其悲哀 2024-08-08 17:32:06

您可以尝试将其插入到sys.path中:

sys.path.insert(0, './lib')
import BoxTime

You can try inserting it in sys.path:

sys.path.insert(0, './lib')
import BoxTime
你曾走过我的故事 2024-08-08 17:32:06

我写下这些是因为每个人似乎都建议您必须创建一个 lib 目录。

您不需要将子目录命名为lib。 只要将 __init__.py 放入其中,您就可以将其命名为任何

您可以通过在 linux shell 中输入以下命令来做到这一点:

$ touch anything/__init__.py 

现在您有了这样的结构:

$ ls anything/
__init__.py
mylib.py

$ ls
main.py

然后您可以将 mylib 导入到 main.py 中,如下所示:

from anything import mylib 

mylib.myfun()

您还可以像这样导入函数和类:

from anything.mylib import MyClass
from anything.mylib import myfun

instance = MyClass()
result = myfun()

您放置在 __init__.py 中的任何变量函数或类也可以被访问:

import anything

print(anything.myvar)

或者像这样:

from anything import myvar

print(myvar)

I am writing this down because everyone seems to suggest that you have to create a lib directory.

You don't need to name your sub-directory lib. You can name it anything provided you put an __init__.py into it.

You can do that by entering the following command in a linux shell:

$ touch anything/__init__.py 

So now you have this structure:

$ ls anything/
__init__.py
mylib.py

$ ls
main.py

Then you can import mylib into main.py like this:

from anything import mylib 

mylib.myfun()

You can also import functions and classes like this:

from anything.mylib import MyClass
from anything.mylib import myfun

instance = MyClass()
result = myfun()

Any variable function or class you place inside __init__.py can also be accessed:

import anything

print(anything.myvar)

Or like this:

from anything import myvar

print(myvar)
苏辞 2024-08-08 17:32:06

包含完整示例

这基本上涵盖了所有情况(确保您在relative/path/to/your/lib/folder中有__init__.py):

import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/relative/path/to/your/lib/folder")
import someFileNameWhichIsInTheFolder
...
somefile.foo()

示例:< /strong>

您的项目文件夹中有:

/root/myproject/app.py

您的另一个项目文件夹中有:

/root/anotherproject/utils.py
/root/anotherproject/__init__.py

您想要使用 /root/anotherproject/utils.py 并调用其中的 foo 函数。

所以你在app.py中写:

import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../anotherproject")
import utils

utils.foo()

Full example included

This basically covers all cases (make sure you have __init__.py in relative/path/to/your/lib/folder):

import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/relative/path/to/your/lib/folder")
import someFileNameWhichIsInTheFolder
...
somefile.foo()

Example:

You have in your project folder:

/root/myproject/app.py

You have in another project folder:

/root/anotherproject/utils.py
/root/anotherproject/__init__.py

You want to use /root/anotherproject/utils.py and call foo function which is in it.

So you write in app.py:

import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../anotherproject")
import utils

utils.foo()
思念满溢 2024-08-08 17:32:06

您的 lib 目录是否包含 __init__.py 文件?

Python 使用 __init__.py 来确定目录是否是模块。

Does your lib directory contain a __init__.py file?

Python uses __init__.py to determine if a directory is a module.

泛滥成性 2024-08-08 17:32:06

尝试导入.lib.BoxTime。 有关相对导入的更多信息,请阅读 PEP 328

Try import .lib.BoxTime. For more information read about relative import in PEP 328.

以歌曲疗慰 2024-08-08 17:32:06

在子目录/lib 中创建一个空文件__init__.py
在主代码的开头添加

from __future__ import absolute_import 

然后

import lib.BoxTime as BT
...
BT.bt_function()

或者更好

from lib.BoxTime import bt_function
...
bt_function()

Create an empty file __init__.py in subdirectory /lib.
And add at the begin of main code

from __future__ import absolute_import 

then

import lib.BoxTime as BT
...
BT.bt_function()

or better

from lib.BoxTime import bt_function
...
bt_function()
小鸟爱天空丶 2024-08-08 17:32:06

只是对这些答案的补充。

如果您想导入所有子目录中的所有文件,您可以将其添加到文件的根目录中。

import sys, os
sys.path.extend([f'./{name}' for name in os.listdir(".") if os.path.isdir(name)])

然后您可以简单地从子目录导入文件,就像这些文件位于当前目录中一样。

工作示例

如果我的项目中有以下带有子目录的目录...

.
├── a.py
├── b.py
├── c.py
├── subdirectory_a
│   ├── d.py
│   └── e.py
├── subdirectory_b
│   └── f.py
├── subdirectory_c
│   └── g.py
└── subdirectory_d
    └── h.py

我可以将以下代码放入我的 a.py 文件中

import sys, os
sys.path.extend([f'./{name}' for name in os.listdir(".") if os.path.isdir(name)])

# And then you can import files just as if these files are inside the current directory

import b
import c
import d
import e
import f
import g
import h

换句话说,此代码将从文件所在的目录中抽象出来从。

Just an addition to these answers.

If you want to import all files from all subdirectories, you can add this to the root of your file.

import sys, os
sys.path.extend([f'./{name}' for name in os.listdir(".") if os.path.isdir(name)])

And then you can simply import files from the subdirectories just as if these files are inside the current directory.

Working example

If I have the following directory with subdirectories in my project...

.
├── a.py
├── b.py
├── c.py
├── subdirectory_a
│   ├── d.py
│   └── e.py
├── subdirectory_b
│   └── f.py
├── subdirectory_c
│   └── g.py
└── subdirectory_d
    └── h.py

I can put the following code inside my a.py file

import sys, os
sys.path.extend([f'./{name}' for name in os.listdir(".") if os.path.isdir(name)])

# And then you can import files just as if these files are inside the current directory

import b
import c
import d
import e
import f
import g
import h

In other words, this code will abstract from which directory the file is coming from.

2024-08-08 17:32:06

对于此文件夹层次结构图示例:

/project/tester.py    
/project/lib/BoxTime.py

1- 在 lib 文件夹内创建一个空白 py 文件 __init__.py

2- 在调用方 py 文件 tester.py 中添加这些代码行

import os, sys
sys.path.insert(0,'lib')# insert the folder lib in system path
from BoxTime import Function_name # from the py file import the needed function

简单解释可以在此处找到。

注意:这称为在不同文件夹中创建/导入模块。

个人经验:我尝试从jupyter笔记本创建模块,但它不起作用(也许我使用.ipynb做得不正确),我需要在juypyter笔记本之外手动创建模块,或者使用其他IDE(例如pycharm)。

For this folder hierarchy diagram example:

/project/tester.py    
/project/lib/BoxTime.py

1- Create a blank py file __init__.py inside lib folder

2- In the caller py file tester.py add theses code lines

import os, sys
sys.path.insert(0,'lib')# insert the folder lib in system path
from BoxTime import Function_name # from the py file import the needed function

Easy explanation can be found in here.

Notice: This is refered to as creating/importing modules in/from different folder.

Personel experience: I tried to create module from jupyter notebook, it did not not work (maybe I done it improperly using .ipynb), I needed to do it manually outside the juypyter notebook, or using other IDE (e.g. pycharm).

彻夜缠绵 2024-08-08 17:32:06

create_card.py

 init():
   print('Hello world!')

app.py

import create_card

create_card.init()

如果您只想导入必需的函数

from create_card import init

如果您有嵌套目录(例如:modules/aadhaar/create-card.py)

import module.aadhaar.create_card as create_card从modules.aadhaar.create_card导入init

create_card.py

 init():
   print('Hello world!')

app.py

import create_card

create_card.init()

if you want to import only required functions

from create_card import init

If you have nested directories (Ex: modules/aadhaar/create-card.py)

import modules.aadhaar.create_card as create_card or from modules.aadhaar.create_card import init

别闹i 2024-08-08 17:32:06

/project/tester.py

/project/lib/BoxTime.py

创建空白文件 __init__.py 直到到达文件

< code>/project/lib/somefolder/BoxTime.py

#lib -- 需要有两项,一个是 __init__.py 和一个名为 somefolder 的目录
#somefolder 有两个项目 boxtime.py__init__.py

/project/tester.py

/project/lib/BoxTime.py

create blank file __init__.py down the line till you reach the file

/project/lib/somefolder/BoxTime.py

#lib -- needs has two items one __init__.py and a directory named somefolder
#somefolder has two items boxtime.py and __init__.py

帅冕 2024-08-08 17:32:06

试试这个:

from lib import BoxTime

try this:

from lib import BoxTime

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文