如何在Python中导入文件?我想导入:
文件(例如file.py) 一个文件夹 在运行时根据用户输入动态地生成文件 文件的特定部分(例如,单个函数)
如何在Python中导入文件?我想导入:
文件(例如file.py) 一个文件夹 在运行时根据用户输入动态地生成文件 文件的特定部分(例如,单个函数)
当前回答
这帮助我用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
对于其他系统,更全面的答案也在这个问题中。
其他回答
import sys
#print(sys.path)
sys.path.append('../input/tokenization')
import tokenization
要导入任何.py文件,可以使用上面的代码。
首先追加路径,然后导入
注:“. ./input/tokenization'目录中包含tokenization.py文件
只是在另一个python文件中导入python文件
假设我有一个help .py python文件,它有一个显示函数,
def display():
print("I'm working sundar gsv")
在app.py中,你可以使用display函数,
import helper
helper.display()
输出,
我正在工作,桑达gsv
注意:不需要指定.py扩展名。
有很多方法,如上所述,但我发现我只想导入文件的内容,而不希望必须写一行又一行,必须导入其他模块。因此,我想出了一种方法来获取文件的内容,甚至使用点语法(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即可。
希望这对你有所帮助。 石磊
有几种方法可以将python脚本包含在abc.py中
例如,如果你的文件名为abc.py(导入abc) 限制是你的文件应该和你调用的python脚本在同一个位置。
进口美国广播公司
例如,如果你的python文件在Windows文件夹中。Windows文件夹与调用python脚本的位置相同。
从文件夹导入ABC
在情况下abc.py脚本是可用的内部internal_folder,是在文件夹内
导入ABC
正如James上面所回答的,如果你的文件在某个固定的位置
进口操作系统 导入系统 scriptpath = "../Test/MyModule.py" sys.path.append (os.path.abspath (scriptpath)) 进口MyModule里
如果你的python脚本更新了,你不想上传-使用这些语句自动刷新。好处:)
%load_ext autoreload
%autoreload 2
导入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