如何在Python中导入文件?我想导入:

文件(例如file.py) 一个文件夹 在运行时根据用户输入动态地生成文件 文件的特定部分(例如,单个函数)


当前回答

在“运行时”导入一个已知名称的特定Python文件:

import os
import sys

...

scriptpath = "../Test/"

# Add the directory containing your module to the Python path (wants absolute paths)
sys.path.append(os.path.abspath(scriptpath))

# Do the import
import MyModule

其他回答

导入.py文件的最佳方法是使用__init__.py。最简单的方法是在你的.py文件所在的目录下创建一个名为__init__.py的空文件。

Mike Grouchy的这篇文章很好地解释了__init__.py及其用于制作、导入和设置python包的用法。

在“运行时”导入一个已知名称的特定Python文件:

import os
import sys

...

scriptpath = "../Test/"

# Add the directory containing your module to the Python path (wants absolute paths)
sys.path.append(os.path.abspath(scriptpath))

# Do the import
import MyModule

导入文件..——参考链接

需要__init__.py文件来使Python将目录视为包含包,这样做是为了防止具有通用名称的目录,如string,在无意中隐藏了模块搜索路径中稍后出现的有效模块。

__init__.py可以只是一个空文件,但它也可以执行包的初始化代码或设置__all__变量。

mydir/spam/__init__.py
mydir/spam/module.py
import spam.module
or
from spam import module

只是在另一个python文件中导入python文件

假设我有一个help .py python文件,它有一个显示函数,

def display():
    print("I'm working sundar gsv")

在app.py中,你可以使用display函数,

import helper
helper.display()

输出,

我正在工作,桑达gsv

注意:不需要指定.py扩展名。

这帮助我用Visual Studio Code构建我的Python项目。

当你没有在目录中声明__init__.py时,可能会导致这个问题。目录变成隐式的名称空间包。下面是关于Python导入和项目结构的一个很好的总结。

另外,如果你想使用顶部栏中的Visual Studio Code运行按钮,脚本不在主包中,你可以尝试从实际目录运行控制台。

例如,你想要从测试包中执行一个打开的test_game_item.py,并且你有Visual Studio Code在省略(主包)目录中打开:

├── omission
│   ├── app.py
│   ├── common
│   │   ├── classproperty.py
│   │   ├── constants.py
│   │   ├── game_enums.py
│   │   └── __init__.py
│   ├── game
│   │   ├── content_loader.py
│   │   ├── game_item.py
│   │   ├── game_round.py
│   │   ├── __init__.py
│   │   └── timer.py
│   ├── __init__.py
│   ├── __main__.py
│   ├── resources
│   └── tests
│       ├── __init__.py
│       ├── test_game_item.py
│       ├── test_game_round_settings.py
│       ├── test_scoreboard.py
│       ├── test_settings.py
│       ├── test_test.py
│       └── test_timer.py
├── pylintrc
├── README.md
└── .gitignore

目录结构来自[2]。

你可以试着这样设置:

(Windows) Ctrl + Shift + P→Preferences: Open Settings (JSON)。

将这一行添加到用户设置中:

"python.terminal.executeInFileDir": true

对于其他系统,更全面的答案也在这个问题中。