我这样做:
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所以我通过它应该没事,不应该吗?
我究竟做错了什么?
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")
)