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

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


当前回答

import sys
#print(sys.path)
sys.path.append('../input/tokenization')
import tokenization

要导入任何.py文件,可以使用上面的代码。

首先追加路径,然后导入

注:“. ./input/tokenization'目录中包含tokenization.py文件

其他回答

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

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

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

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

在“运行时”导入一个已知名称的特定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
from file import function_name  ######## Importing specific function
function_name()                 ######## Calling function

and

import file              ######## Importing whole package
file.function1_name()    ######## Calling function
file.function2_name()    ######## Calling function

以下是我现在已经理解的两种简单方法,确保你想导入的“file.py”文件只存在于你的当前目录中。

我想补充一点,我在其他地方不太清楚;在模块/包中,当从文件中加载时,模块/包名必须以mymodule作为前缀。想象我的模块是这样布局的:

/main.py
/mymodule
    /__init__.py
    /somefile.py
    /otherstuff.py

当从__init__.py加载somefile.py/otherstuff.py时,内容应该如下所示:

from mymodule.somefile import somefunc
from mymodule.otherstuff import otherfunc

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()