我正在创建一个从压缩文件加载并运行python脚本的程序。除了那些python脚本之外,我还有一个配置文件,我以前使用configparser从程序的未压缩版本中加载信息。在
是否可以使用configparser直接读取zip文件中的配置文件?或者我必须把它解压到一个临时文件夹中然后从那里加载它?在
我试着直接给出路径:
>>> sysconf = configparser.ConfigParser()
>>> sysconf.read_file("compressed.zip/config_data.conf")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/configparser.py", line 691, in read_file
self._read(f, source)
File "/usr/local/lib/python3.4/configparser.py", line 1058, in _read
raise MissingSectionHeaderError(fpname, lineno, line)
configparser.MissingSectionHeaderError: File contains no section headers.
file: '<???>', line: 1
没用。没有惊喜。在
然后我试着用zipfile
^{pr2}$发现它也没用。在
所以我只好创建一个临时文件夹,解压缩到它,然后读取那里的conf文件。如果可能的话,我真的希望避免这种情况,因为conf文件是唯一的限制因素。我现在可以(并且正在)从zip文件加载python模块。在
如果有一种方法可以将文件的原始文本直接传递给configparser,那么我可以获得该文件的原始文本,但是在搜索文档时却空手而归。在
更新: 我尝试使用stringIO作为一个文件对象,它似乎有点作用。 configparser没有拒绝它,但它也不喜欢它。在
>>> zf = zipfile.ZipFile("compressed.zip")
>>> data = zf.read(config_data.conf)
>>> confdata = io.StringIO(str(data))
>>> sysconf = configparser.ConfigParser()
>>> sysconf.readfp(confdata)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/configparser.py", line 736, in readfp
self.read_file(fp, source=filename)
File "/usr/local/lib/python3.4/configparser.py", line 691, in read_file
self._read(f, source)
File "/usr/local/lib/python3.4/configparser.py", line 1058, in _read
raise MissingSectionHeaderError(fpname, lineno, line)
configparser.MissingSectionHeaderError: File contains no section headers.
file: '<???>', line: 1
(continues to spit out the entire contents of the file)
如果我使用read_文件,它不会出错,但也不会加载任何内容。在
>>> zf = zipfile.ZipFile("compressed.zip")
>>> data = zf.read(config_data.conf)
>>> confdata = io.StringIO(str(data))
>>> sysconf = configparser.ConfigParser()
>>> sysconf.read_file(confdata)
>>> sysconf.items("General") #(this is the main section in the file)
Traceback (most recent call last):
File "/usr/local/lib/python3.4/configparser.py", line 824, in items
d.update(self._sections[section])
KeyError: 'General'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/configparser.py", line 827, in items
raise NoSectionError(section)
configparser.NoSectionError: No section: 'General'
尝试^{}
与适当的ZIP文件结合使用时,以下代码适用于我:
经过深思熟虑,以下可能更合适:
^{pr2}$ZipFile
不仅支持read
,还支持open
,后者返回一个类似文件的对象。所以,你可以这样做:正如评论中所写,@matthewatabet answer不能与python3.4(以及更新的vesions)一起使用。这是因为
ZipFile.open
现在返回一个“类似字节”的对象,而不再是“类似文件”的对象。您可以使用:使用UTF-8编码将
^{pr2}$config_file
字节类型的对象转换为类似文件的对象。代码现在是:这似乎比创建
string
更令人满意,但我不知道它是否更有效。。。在相关问题 更多 >
编程相关推荐