如何在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

其他回答

Python的一个非常不为人知的特性是导入zip文件的能力:

library.zip
|-library
|--__init__.py

该包的__init__.py文件包含以下内容:

def dummy():
    print 'Testing things out...'

我们可以编写另一个脚本,它可以从zip归档文件中导入包。只需要将zip文件添加到sys.path。

import sys
sys.path.append(r'library.zip')

import library

def run():
    library.dummy()

run()

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

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

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

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

import helper
helper.display()

输出,

我正在工作,桑达gsv

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

如果你想导入的模块不在子目录中,那么尝试以下方法并从最深的公共父目录运行app.py:

目录结构:

/path/to/common_dir/module/file.py
/path/to/common_dir/application/app.py
/path/to/common_dir/application/subpath/config.json

在app.py中,将客户端的路径追加到sys.path:

import os, sys, inspect

sys.path.append(os.getcwd())
from module.file import MyClass
instance = MyClass()

可选(如果你加载例如配置)(Inspect似乎是我的用例中最健壮的一个)

# Get dirname from inspect module
filename = inspect.getframeinfo(inspect.currentframe()).filename
dirname = os.path.dirname(os.path.abspath(filename))
MY_CONFIG = os.path.join(dirname, "subpath/config.json")

Run

user@host:/path/to/common_dir$ python3 application/app.py

这个解决方案适用于我的cli,以及PyCharm。

有很多方法,如上所述,但我发现我只想导入文件的内容,而不希望必须写一行又一行,必须导入其他模块。因此,我想出了一种方法来获取文件的内容,甚至使用点语法(file.property),而不是将导入的文件与您的文件合并。 首先,这是我要导入的文件data。py

    testString= "A string literal to import and test with"

注意:您可以使用.txt扩展名。 在mainfile.py中,首先打开并获取内容。

    #!usr/bin/env python3
    Data=open('data.txt','r+').read()

现在您有了字符串形式的内容,但是正在尝试访问数据。testString将导致一个错误,因为data是str类的一个实例,即使它确实有一个属性testString,它也不会执行您所期望的操作。 接下来,创建一个类。例如(双关语),ImportedFile

    class ImportedFile:

然后把这个放进里面(用合适的缩进):

    exec(data)

最后,像这样重新分配数据:

    data=ImportedFile()

就是这样!就像访问任何其他模块一样,输入print(data.testString)将打印到控制台一个字符串文字,用于导入和测试。 然而,如果你想要从mod import *中获得等效的效果,只需删除类、实例赋值和删除exec即可。

希望这对你有所帮助。 石磊

这帮助我用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

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