Python3 configparser从第一个arg开始必须是字节或字节元组,而不是str

问题描述 投票:1回答:1

我这样做:

tar = tarfile.open("stuff.tar")
cfg = configparser.ConfigParser(allow_no_value=True)
cfg.read_file(tar.extractfile("ook.ini"))

文件“ook.ini”确实位于“stuff.tar”存档中。

但是,我明白了:

[…] ← Really not relevant stack trace. It's just where my code calls this.
File "/usr/local/lib/python3.7/configparser.py", line 1030, in _read
    if line.strip().startswith(prefix):
TypeError: startswith first arg must be bytes or a tuple of bytes, not str

根据文件,read_file() read and parse configuration data from f which must be an iterable yielding Unicode strings所以我通过它应该没事,不应该吗?

我究竟做错了什么?

python python-3.x tar configparser
1个回答
3
投票

TarFile.extractfile(member)返回以二进制模式打开的文件。 read_file的等价物是以文本模式打开的文件。因此,两者不匹配。

您可以将提取的文件包装在io.TextIOWrapper或转换为unicode的生成器中:

tar = tarfile.open("stuff.tar")
cfg = configparser.ConfigParser(allow_no_value=True)
cfg.read_file(
    line.decode() for line in tar.extractfile("ook.ini")
)
© www.soinside.com 2019 - 2024. All rights reserved.