如何从Python包中读取(静态)文件? [英] How to read a (static) file from inside a Python package?
本文介绍了如何从Python包中读取(静态)文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您能告诉我如何读取Python软件包中的文件吗?
Could you tell me how can I read a file that is inside my Python package?
我加载的程序包具有许多我想从程序中加载的模板(用作字符串的文本文件).但是,如何指定该文件的路径?
A package that I load has a number of templates (text files used as strings) that I want to load from within the program. But how do I specify the path to such file?
想象一下我想从以下位置读取文件:
Imagine I want to read a file from:
package\templates\temp_file
某种路径操纵?包基本路径跟踪?
Some kind of path manipulation? Package base path tracking?
推荐答案
[添加于2016-06-15:显然,这并非在所有情况下都有效.请参阅其他答案]
[added 2016-06-15: apparently this doesn't work in all situations. please refer to the other answers]
import os, mypackage
template = os.path.join(mypackage.__path__[0], 'templates', 'temp_file')
这篇关于如何从Python包中读取(静态)文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文