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

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


当前回答

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

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

首先追加路径,然后导入

注:“. ./input/tokenization'目录中包含tokenization.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。

导入python文件的方法有很多种,各有优缺点。

不要匆忙地选择第一个适用于您的导入策略,否则当您发现它不能满足您的需求时,您将不得不重写代码库。

我将从解释最简单的示例#1开始,然后转向最专业和最健壮的示例#7

例1,使用python解释器导入python模块:

把它放到/home/el/foo/fox.py: def what_does_the_fox_say (): 打印(“狐狸精”) 进入python解释器: el@apollo: / home / el / foo $ python Python 2.7.3(默认,Sep 26 2013, 20:03:06) >>> import fox > > > fox.what_does_the_fox_say () 狐狸精哭 >>> 您通过python解释器导入了fox,从fox.py中调用了python函数what_does_the_fox_say()。

例2,在脚本中使用execfile或(Python 3中的exec)来执行另一个Python文件:

把它放在/home/el/foo2/mylib.py: def moobar (): 打印(“嗨”) 把它放在/home/el/foo2/main.py中: execfile(“/ home / el / foo2 / mylib.py”) moobar () 运行文件: el@apollo:/home/el/foo$ python main.py 嗨 函数moobar从mylib.py导入,并在main.py中可用

例3,使用from…进口…功能:

把它放在/home/el/foo3/chekov.py: def问题(): 打印“核舰艇在哪里?” 把它放在/home/el/foo3/main.py中: 从契科夫进口问题 问题() 像这样运行它: el@apollo:/home/el/foo3$ python main.py 核潜艇在哪里? 如果你在chekov.py中定义了其他函数,它们将不可用,除非你导入*

例4,如果riaa.py位于不同的文件位置,则导入它

把它放到/home/el/foo4/stuff/riaa.py: def监视(): 打印“计算机正在转变为人类的套索和枷锁” 把它放在/home/el/foo4/main.py中: 导入系统 进口操作系统 sys.path.append (os.path.abspath(“/ home / el / foo4 /东西”)) 从riaa进口* 留神观察() 运行该程序: el@apollo:/home/el/foo4$ python main.py 计算机正在变成人类的绞索和枷锁 它从不同的目录导入外部文件中的所有内容。

例5,使用os。系统(“python yourfile.py”)

import os
os.system("python yourfile.py")

例6,通过装载python startuphook导入你的文件:

更新:此示例过去适用于python2和3,但现在只适用于python2。Python3摆脱了这个用户startuphook特性集,因为它被低技能的python库作者滥用,使用它不礼貌地将他们的代码注入到全局名称空间,在所有用户定义的程序之前。如果您想让它在python3中工作,就必须更有创造性。如果我告诉你怎么做,python开发人员也会禁用该功能集,所以你只能靠自己了。

参见:https://docs.python.org/2/library/user.html

将这段代码放到主目录~/.pythonrc.py中

class secretclass:
    def secretmessage(cls, myarg):
        return myarg + " is if.. up in the sky, the sky"
    secretmessage = classmethod( secretmessage )

    def skycake(cls):
        return "cookie and sky pie people can't go up and "
    skycake = classmethod( skycake )

把这段代码放到你的main.py(可以在任何地方):

import user
msg = "The only way skycake tates good" 
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")

运行它,你应该得到这个:

$ python main.py
The only way skycake tates good is if.. up in the sky, 
the skycookie and sky pie people can't go up and  have the sky pie! 
SKYCAKE!

如果你在这里得到一个错误:ModuleNotFoundError:没有名为'user'的模块,那么这意味着你正在使用python3,启动钩子默认是禁用的。

这篇文章的出处是:https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py请把你的小船送上来。

例7,最健壮的:在python中使用bare Import命令导入文件:

Make a new directory /home/el/foo5/ Make a new directory /home/el/foo5/herp Make an empty file named __init__.py under herp: el@apollo:/home/el/foo5/herp$ touch __init__.py el@apollo:/home/el/foo5/herp$ ls __init__.py Make a new directory /home/el/foo5/herp/derp Under derp, make another __init__.py file: el@apollo:/home/el/foo5/herp/derp$ touch __init__.py el@apollo:/home/el/foo5/herp/derp$ ls __init__.py Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there: def skycake(): print "SkyCake evolves to stay just beyond the cognitive reach of " + "the bulk of men. SKYCAKE!!" The moment of truth, Make the new file /home/el/foo5/main.py, put this in there; from herp.derp.yolo import skycake skycake() Run it: el@apollo:/home/el/foo5$ python main.py SkyCake evolves to stay just beyond the cognitive reach of the bulk of men. SKYCAKE!! The empty __init__.py file communicates to the python interpreter that the developer intends this directory to be an importable package.

如果你想看我关于如何在一个目录下包含所有.py文件的帖子,请参阅这里:https://stackoverflow.com/a/20753073/445131

将python文件从一个文件夹导入到另一个文件夹的复杂方法并不多。只需要创建一个__init__.py文件来声明这个文件夹是一个python包,然后转到你想要导入的主机文件

从root。parent。folder。file导入变量,类,等等

这就是我从python文件调用函数的方式,这对我来说是灵活的,可以调用任何函数。

import os, importlib, sys

def callfunc(myfile, myfunc, *args):
    pathname, filename = os.path.split(myfile)
    sys.path.append(os.path.abspath(pathname))
    modname = os.path.splitext(filename)[0]
    mymod = importlib.import_module(modname)
    result = getattr(mymod, myfunc)(*args)
    return result

result = callfunc("pathto/myfile.py", "myfunc", arg1, arg2)

你也可以这样做:从文件名导入一些东西

示例:from client import客户端 请注意,您不需要.py .pyw .pyui扩展名。