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

文件(例如file.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 3.5或更高版本时,可以使用importlib。Util可以直接将.py文件作为模块导入任意位置,而不需要修改sys.path。

import importlib.util
import sys

def load_module(file_name, module_name)
    spec = importlib.util.spec_from_file_location(module_name, file_name)
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module

参数file_name必须为字符串或类路径对象。module_name参数是必需的,因为所有加载的Python模块都必须有一个(点)模块名(如sys、importlib或importlib.util),但您可以为这个新模块选择任何可用的名称。

你可以这样使用这个函数:

my_module = load_module("file.py", "mymod")

在使用load_module()函数将该模块导入Python进程一次之后,就可以使用给定的模块名导入该模块。

file.py:

print(f"file.py was imported as {__name__}")

one.py:

print(f"one.py was imported as {__name__}")
load_module("file.py", "mymod")
import two

two.py:

print(f"two.py was imported as {__name__})")
import mymod

对于上面的文件,您可以运行以下命令来查看file.py如何变得可导入。

$ python3 -m one
one.py was imported as __main__
two.py was imported as two
file.py was imported as mymod

这个答案基于官方的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

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

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

导入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

有很多方法,如上所述,但我发现我只想导入文件的内容,而不希望必须写一行又一行,必须导入其他模块。因此,我想出了一种方法来获取文件的内容,甚至使用点语法(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即可。

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