如何导入其他Python文件?

问题:如何导入其他Python文件?

如何在Python中导入其他文件?

  1. 我到底该如何导入特定的python文件import file.py呢?
  2. 如何导入文件夹而不是特定文件?
  3. 我想根据用户输入在运行时动态加载Python文件。
  4. 我想知道如何从文件中仅加载一个特定部分。

例如,在main.py我有:

from extra import * 

尽管这给了我中的所有定义extra.py,但也许我只想要一个定义:

def gap():
    print
    print

我要从import语句中添加什么?gapextra.py

How do I import other files in Python?

  1. How exactly can I import a specific python file like import file.py?
  2. How can I import a folder instead of a specific file?
  3. I want to load a Python file dynamically at runtime, based on user input.
  4. I want to know how to load just one specific part from the file.

For example, in main.py I have:

from extra import * 

Although this gives me all the definitions in extra.py, when maybe all I want is a single definition:

def gap():
    print
    print

What do I add to the import statement to just get gap from extra.py?


回答 0

importlib已添加到Python 3中,以编程方式导入模块。它只是一个包装__import__,请参阅文档

import importlib

moduleName = input('Enter module name:')
importlib.import_module(moduleName)

注意:.py扩展名应从中删除moduleName。该函数还package为相对导入定义了一个参数。


更新:以下答案已过时。使用上面的最新替代方法。

  1. 只是import file没有’.py’扩展名。

  2. 您可以通过添加一个名为的空文件来将文件夹标记为包__init__.py

  3. 您可以使用该__import__功能。它以模块名称作为字符串。(同样:模块名称不带“ .py”扩展名。)

    pmName = input('Enter module name:')
    pm = __import__(pmName)
    print(dir(pm))
    

    输入help(__import__)以获取更多详细信息。

importlib was added to Python 3 to programmatically import a module. It is just a wrapper around __import__, see the docs.

import importlib

moduleName = input('Enter module name:')
importlib.import_module(moduleName)

Note: the .py extension should be removed from moduleName. The function also defines a package argument for relative imports.


Update: Answer below is outdated. Use the more recent alternative above.

  1. Just import file without the ‘.py’ extension.

  2. You can mark a folder as a package, by adding an empty file named __init__.py.

  3. You can use the __import__ function. It takes the module name as a string. (Again: module name without the ‘.py’ extension.)

    pmName = input('Enter module name:')
    pm = __import__(pmName)
    print(dir(pm))
    

    Type help(__import__) for more details.


回答 1

导入python文件的方法有很多,各有利弊。

不要只是匆忙地选择适合您的第一个导入策略,否则您将不得不在以后发现无法满足您的需要时重写代码库。

我将首先说明最简单的示例#1,然后将介绍最专业,最可靠的示例#7

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

  1. 将其放在/home/el/foo/fox.py中:

    def what_does_the_fox_say():
      print("vixens cry")
  2. 进入python解释器:

    el@apollo:/home/el/foo$ python
    Python 2.7.3 (default, Sep 26 2013, 20:03:06) 
    >>> import fox
    >>> fox.what_does_the_fox_say()
    vixens cry
    >>> 

    您通过python解释器导入了fox,并what_does_the_fox_say()从fox.py中调用了python函数。

示例2,在脚本中使用execfile或(exec在Python 3中)在适当的位置执行另一个python文件:

  1. 将其放在/home/el/foo2/mylib.py中:

    def moobar():
      print("hi")
  2. 将其放在/home/el/foo2/main.py中:

    execfile("/home/el/foo2/mylib.py")
    moobar()
  3. 运行文件:

    el@apollo:/home/el/foo$ python main.py
    hi

    功能moobar是从mylib.py导入的,并在main.py中可用

示例3,从…使用…导入…功能:

  1. 将其放在/home/el/foo3/chekov.py中:

    def question():
      print "where are the nuclear wessels?"
  2. 将其放在/home/el/foo3/main.py中:

    from chekov import question
    question()
  3. 像这样运行它:

    el@apollo:/home/el/foo3$ python main.py 
    where are the nuclear wessels?

    如果您在chekov.py中定义了其他函数,除非您定义了这些函数,否则它们将不可用。 import *

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

  1. 将其放在/home/el/foo4/stuff/riaa.py中:

    def watchout():
      print "computers are transforming into a noose and a yoke for humans"
  2. 将其放在/home/el/foo4/main.py中:

    import sys 
    import os
    sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
    from riaa import *
    watchout()
  3. 运行:

    el@apollo:/home/el/foo4$ python main.py 
    computers are transforming into a noose and a yoke for humans

    那会从另一个目录导入外部文件中的所有内容。

示例5,使用 os.system("python yourfile.py")

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

示例6,通过piggy带python startuphook导入文件:

更新:此示例曾经同时适用于python2和3,但现在仅适用于python2。python3摆脱了此用户启动钩子功能集,因为它被低技能的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: No module named 'user'这意味着您正在使用python3,默认情况下会禁用启动钩。

值得一提的是:https : //github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py随便 发送。

示例7,最健壮:使用裸导入命令在python中导入文件:

  1. 建立一个新目录 /home/el/foo5/
  2. 建立一个新目录 /home/el/foo5/herp
  3. 制作一个以__init__.pyherp 命名的空文件:

    el@apollo:/home/el/foo5/herp$ touch __init__.py
    el@apollo:/home/el/foo5/herp$ ls
    __init__.py
  4. 新建一个目录/ home / el / foo5 / herp / derp

  5. 在derp下,制作另一个__init__.py文件:

    el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
    el@apollo:/home/el/foo5/herp/derp$ ls
    __init__.py
  6. 在/ home / el / foo5 / herp / derp下,创建一个名为yolo.pyPut this 的新文件:

    def skycake():
      print "SkyCake evolves to stay just beyond the cognitive reach of " +
      "the bulk of men. SKYCAKE!!"
  7. 关键时刻,创建新文件/home/el/foo5/main.py,并将其放入其中;

    from herp.derp.yolo import skycake
    skycake()
  8. 运行:

    el@apollo:/home/el/foo5$ python main.py
    SkyCake evolves to stay just beyond the cognitive reach of the bulk 
    of men. SKYCAKE!!

    __init__.py文件会通知python解释器开发人员打算将此目录作为可导入包。

如果您想查看我的帖子,如何在目录下包含所有.py文件,请参见此处:https : //stackoverflow.com/a/20753073/445131

There are many ways to import a python file, all with their pros and cons.

Don’t just hastily pick the first import strategy that works for you or else you’ll have to rewrite the codebase later on when you find it doesn’t meet your needs.

I’ll start out explaining the easiest example #1, then I’ll move toward the most professional and robust example #7

Example 1, Import a python module with python interpreter:

  1. Put this in /home/el/foo/fox.py:

    def what_does_the_fox_say():
      print("vixens cry")
    
  2. Get into the python interpreter:

    el@apollo:/home/el/foo$ python
    Python 2.7.3 (default, Sep 26 2013, 20:03:06) 
    >>> import fox
    >>> fox.what_does_the_fox_say()
    vixens cry
    >>> 
    

    You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.

Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:

  1. Put this in /home/el/foo2/mylib.py:

    def moobar():
      print("hi")
    
  2. Put this in /home/el/foo2/main.py:

    execfile("/home/el/foo2/mylib.py")
    moobar()
    
  3. run the file:

    el@apollo:/home/el/foo$ python main.py
    hi
    

    The function moobar was imported from mylib.py and made available in main.py

Example 3, Use from … import … functionality:

  1. Put this in /home/el/foo3/chekov.py:

    def question():
      print "where are the nuclear wessels?"
    
  2. Put this in /home/el/foo3/main.py:

    from chekov import question
    question()
    
  3. Run it like this:

    el@apollo:/home/el/foo3$ python main.py 
    where are the nuclear wessels?
    

    If you defined other functions in chekov.py, they would not be available unless you import *

Example 4, Import riaa.py if it’s in a different file location from where it is imported

  1. Put this in /home/el/foo4/stuff/riaa.py:

    def watchout():
      print "computers are transforming into a noose and a yoke for humans"
    
  2. Put this in /home/el/foo4/main.py:

    import sys 
    import os
    sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
    from riaa import *
    watchout()
    
  3. Run it:

    el@apollo:/home/el/foo4$ python main.py 
    computers are transforming into a noose and a yoke for humans
    

    That imports everything in the foreign file from a different directory.

Example 5, use os.system("python yourfile.py")

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

Example 6, import your file via piggybacking the python startuphook:

Update: This example used to work for both python2 and 3, but now only works for python2. python3 got rid of this user startuphook feature set because it was abused by low-skill python library writers, using it to impolitely inject their code into the global namespace, before all user-defined programs. If you want this to work for python3, you’ll have to get more creative. If I tell you how to do it, python developers will disable that feature set as well, so you’re on your own.

See: https://docs.python.org/2/library/user.html

Put this code into your home directory in ~/.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 )

Put this code into your main.py (can be anywhere):

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!")

Run it, you should get this:

$ 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!

If you get an error here: ModuleNotFoundError: No module named 'user' then it means you’re using python3, startuphooks are disabled there by default.

Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py Send along your up-boats.

Example 7, Most Robust: Import files in python with the bare import command:

  1. Make a new directory /home/el/foo5/
  2. Make a new directory /home/el/foo5/herp
  3. 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
    
  4. Make a new directory /home/el/foo5/herp/derp

  5. 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
    
  6. 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!!"
    
  7. The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;

    from herp.derp.yolo import skycake
    skycake()
    
  8. 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.

If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131


回答 2

要在“运行时”以已知名称导入特定的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

To import a specific Python file at ‘runtime’ with a known name:

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

回答 3

您没有很多复杂的方法可以将python文件从一个文件夹导入到另一个文件夹。只需创建一个__init__.py文件,以声明此文件夹为python软件包,然后转到要导入的主机文件即可,只需键入

from root.parent.folder.file import variable, class, whatever

You do not have many complex methods to import a python file from one folder to another. Just create a __init__.py file to declare this folder is a python package and then go to your host file where you want to import just type

from root.parent.folder.file import variable, class, whatever


回答 4

导入文档..-链接以供参考

__init__.py需要这些文件才能使Python将目录视为包含软件包的目录,这样做是为了防止具有通用名称(例如字符串)的目录无意间隐藏了稍后在模块搜索路径中出现的有效模块。

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

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

Import doc .. — Link for reference

The __init__.py files are required to make Python treat the directories as containing packages, this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

__init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.

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

回答 5

第一种情况:您要在file A.py中导入文件B.py,这两个文件位于同一文件夹中,如下所示:

. 
├── A.py 
└── B.py

您可以在file中执行此操作B.py

import A

要么

from A import *

要么

from A import THINGS_YOU_WANT_TO_IMPORT_IN_A

然后,您将可以使用文件A.py中文件的所有功能B.py


第二种情况:您要在file folder/A.py中导入文件B.py,这两个文件不在同一文件夹中,如下所示:

.
├── B.py
└── folder
     └── A.py

您可以在文件B中执行此操作:

import folder.A

要么

from folder.A import *

要么

from folder.A import THINGS_YOU_WANT_TO_IMPORT_IN_A

然后,您将可以使用文件A.py中文件的所有功能B.py


摘要:在第一种情况下,file A.py是您在file中导入的模块,B.py使用了语法import module_name。在第二种情况下,使用的语法folder是包含模块的软件包。A.pyimport package_name.module_name

有关软件包和模块的更多信息,请参考此链接

First case: You want to import file A.py in file B.py, these two files are in the same folder, like this:

. 
├── A.py 
└── B.py

You can do this in file B.py:

import A

or

from A import *

or

from A import THINGS_YOU_WANT_TO_IMPORT_IN_A

Then you will be able to use all the functions of file A.py in file B.py


Second case: You want to import file folder/A.py in file B.py, these two files are not in the same folder, like this:

.
├── B.py
└── folder
     └── A.py

You can do this in file B:

import folder.A

or

from folder.A import *

or

from folder.A import THINGS_YOU_WANT_TO_IMPORT_IN_A

Then you will be able to use all the functions of file A.py in file B.py


Summary: In the first case, file A.py is a module that you imports in file B.py, you used the syntax import module_name. In the second case, folder is the package that contains the module A.py, you used the syntax import package_name.module_name.

For more info on packages and modules, consult this link.


回答 6

from file import function_name  ######## Importing specific function
function_name()                 ######## Calling function

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

这是到目前为止我已经了解的两种简单方法,请确保要导入为库的“ file.py”文件仅存在于当前目录中。

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

Here are the two simple ways I have understood by now and make sure your “file.py” file which you want to import as a library is present in your current directory only.


回答 7

如果定义的函数在文件中x.py

def greet():
    print('Hello! How are you?')

在要导入函数的文件中,编写以下代码:

from x import greet

如果您不希望将所有功能导入文件中,这将很有用。

If the function defined is in a file x.py:

def greet():
    print('Hello! How are you?')

In the file where you are importing the function, write this:

from x import greet

This is useful if you do not wish to import all the functions in a file.


回答 8

导入.py文件的最佳方法是通过__init__.py。最简单的操作是__init__.py在your.py文件所在的目录中创建一个名为空文件。

Mike Grouchy的这篇文章很好地解释了__init__.py它在制作,导入和设置python包中的用途。

the best way to import .py files is by way of __init__.py. the simplest thing to do, is to create an empty file named __init__.py in the same directory that your.py file is located.

this post by Mike Grouchy is a great explanation of __init__.py and its use for making, importing, and setting up python packages.


回答 9

我的导入方式是导入文件并使用其名称的缩写。

import DoStuff.py as DS
DS.main()

不要忘记您的导入文件必须以.py扩展名命名

How I import is import the file and use shorthand of it’s name.

import DoStuff.py as DS
DS.main()

Don’t forget that your importing file MUST BE named with .py extension


回答 10

我想在其他地方加一个不太清楚的注释。在模块/软件包内部,从文件加载时,模块/软件包名称必须带有前缀mymodule。想象一下mymodule这样的布局:

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

从内容中加载somefile.py/ 时应如下所示:otherstuff.py__init__.py

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

I’d like to add this note I don’t very clearly elsewhere; inside a module/package, when loading from files, the module/package name must be prefixed with the mymodule. Imagine mymodule being layout like this:

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

When loading somefile.py/otherstuff.py from __init__.py the contents should look like:

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

回答 11

如果要导入的模块不在子目录中,请尝试以下操作并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()

可选(如果您加载例如configs)(对于我的用例,检查似乎是最可靠的一种)

# 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")

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

此解决方案在cli和PyCharm中都对我有效。

In case the module you want to import is not in a sub-directory, then try the following and run app.py from the deepest common parent directory:

Directory Structure:

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

In app.py, append path of client to sys.path:

import os, sys, inspect

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

Optional (If you load e.g. configs) (Inspect seems to be the most robust one for my use cases)

# 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

This solution works for me in cli, as well as PyCharm.


回答 12

有几种方法可以包含名称为abc.py的python脚本

  1. 例如,如果您的文件名为abc.py(导入abc),则限制是文件应位于与您的调用python脚本相同的位置。

导入abc

  1. 例如,如果您的python文件位于Windows文件夹中。Windows文件夹位于您调用Python脚本的位置。

从文件夹导入abc

  1. 如果abc.py脚本在文件夹中存在的Insider Internal_folder内部可用

从folder.internal_folder导入abc

  1. 如上文James所述,如果您的文件位于某个固定位置

import os
import sys
scriptpath =“ ../Test/MyModule.py”
sys.path.append(os.path.abspath(scriptpath))
import MyModule

如果您的python脚本已更新并且不想上传,请使用这些语句进行自动刷新。奖金:)

%load_ext autoreload 
%autoreload 2

There are couple of ways of including your python script with name abc.py

  1. e.g. if your file is called abc.py (import abc) Limitation is that your file should be present in the same location where your calling python script is.

import abc

  1. e.g. if your python file is inside the Windows folder. Windows folder is present at the same location where your calling python script is.

from folder import abc

  1. Incase abc.py script is available insider internal_folder which is present inside folder

from folder.internal_folder import abc

  1. As answered by James above, in case your file is at some fixed location

import os
import sys
scriptpath = “../Test/MyModule.py”
sys.path.append(os.path.abspath(scriptpath))
import MyModule

In case your python script gets updated and you don’t want to upload – use these statements for auto refresh. Bonus :)

%load_ext autoreload 
%autoreload 2

回答 13

只是为了将python文件导入另一个python文件

可以说我有一个具有显示功能的helper.py python文件,

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

现在在app.py中,您可以使用显示功能,

import helper
helper.display()

输出,

I'm working sundar gsv

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

Just to import python file in another python file

lets say I have helper.py python file which has a display function like,

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

Now in app.py, you can use the display function,

import helper
helper.display()

The output,

I'm working sundar gsv

NOTE: No need to specify the .py extension.


回答 14

这听起来很疯狂,但是如果您只是要为其创建包装脚本,则可以仅创建指向要导入文件的符号链接。

This may sound crazy but you can just create a symbolic link to the file you want to import if you’re just creating a wrapper script to it.


回答 15

您也可以这样做: from filename import something

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

You can also do this: from filename import something

example: from client import Client Note that you do not need the .py .pyw .pyui extension.


回答 16

这就是我从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)

This is how I did to call a function from a python file, that is flexible for me to call any functions.

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)

回答 17

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

现在,您已将内容作为字符串保存,但是尝试访问data.testString将导致错误,就像该类data的实例一样str,即使它确实具有属性testString,也无法实现您期望的效果。
接下来,创建一个类。例如(双关语意图),ImportedFile

    class ImportedFile:

并放入其中(带有适当的缩进):

    exec(data)


最后,data像这样重新分配:

    data=ImportedFile()

就是这样!就像访问其他模块一样进行访问,print(data.testString)将在控制台上输入内容A string literal to import and test with
但是,如果您from mod import *只想删除类,实例分配并取消缩进,则等效于exec

希望这会
有所帮助:)-Benji

There are many ways, as listed above, but I find that I just want to import he contents of a file, and don’t want to have to write lines and lines and have to import other modules. So, I came up with a way to get the contents of a file, even with the dot syntax (file.property) as opposed to merging the imported file with yours.
First of all, here is my file which I’ll import, data.py

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


Note: You could use the .txt extension instead.
In mainfile.py, start by opening and getting the contents.

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

Now you have the contents as a string, but trying to access data.testString will cause an error, as data is an instance of the str class, and even if it does have a property testString it will not do what you expected.
Next, create a class. For instance (pun intended), ImportedFile

    class ImportedFile:

And put this into it (with the appropriate indentation):

    exec(data)


And finally, re-assign data like so:

    data=ImportedFile()

And that’s it! Just access like you would for any-other module, typing print(data.testString) will print to the console A string literal to import and test with.
If, however, you want the equivalent of from mod import * just drop the class, instance assignment, and de-dent the exec.

Hope this helps:)
-Benji


回答 18

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

One very unknown feature of Python is the ability to import zip files:

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

The file __init__.py of the package contains the following:

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

We can write another script which can import a package from the zip archive. It is only necessary to add the zip file to the sys.path.

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

import library

def run():
    library.dummy()

run()