How to access files inside a Python egg file?

守給你的承諾、 提交于 2019-11-28 02:33:41

问题


This might be a weird requirement but it's what I've run into. I Googled but yield nothing.

I'm coding an application who's using a lot of constant attributes / values recorded in an XML file (they'll not change so a static file), things work fine until I generated an egg file for it.

When the logic reaches the XML accessing part, I got one complaint like this: /home/Workspace/my_proj/dist/mps-1.2.0_M2-py2.6.egg/mps/par/client/syntax/syntax.xml

Actually I've bundled the XML file in the path above but seems Python doesn't know how to access it.

The code to access the XML is as...

file_handler = open(path_to_the_file)
lines = file_handler.read().splitlines()

Any idea?


回答1:


egg files are zipfiles, so you must access "stuff" inside them with the zipfile module of the Python standard libraries, not with the built-in open function!




回答2:


If you want to access the contents inside the .egg file you can simply rename it and change extension from .egg to .zip and than unzip it. Which will create a folder and the contents will be same as they were when it was a .egg file

for example brewer2mpl-1.4.1-py3.6.egg
After Renaming brewer2mpl-1.4.1-py3.6.zip

Now if we open it, it'll get easily unzipped and the content will be put in a folder with same name in the same directory. (tested on macOS Sierra)




回答3:


Access file from inside egg file

Yes, It is possible to read the files from inside egg file.

Egg file: mps-1.2.0_M2-py2.6.egg structure for module level example:

In driverfile.py:

import xml.etree.ElementTree
import mps.par.client as syntaxpath
import os
path = os.path.dirname(syntaxpath.__file__)
element = xml.etree.ElementTree.parse(path+'\\syntax\\syntax.xml').getroot()
print(element)

Read xml file from inside an eggfile:

PYTHONPATH=mps-1.2.0_M2-py2.6.egg python driverfile.py




回答4:


just use unzip file.egg this should be enough.




回答5:


i think by default eggs packing file under python won't add your xml inside to the pack



来源:https://stackoverflow.com/questions/3655352/how-to-access-files-inside-a-python-egg-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!