[英]Python3 configparser startswith first arg must be bytes or a tuple of bytes, not str
I am doing this: 我这样做:
tar = tarfile.open("stuff.tar")
cfg = configparser.ConfigParser(allow_no_value=True)
cfg.read_file(tar.extractfile("ook.ini"))
The file "ook.ini" is indeed inside the "stuff.tar" archive. 文件“ook.ini”确实位于“stuff.tar”存档中。
However, I get this: 但是,我明白了:
[…] ← 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
According to the docs, read_file()
read and parse configuration data from f which must be an iterable yielding Unicode strings so what I am passing it should be fine, shouldn't it? 根据文档, read_file()
从f中读取和解析配置数据,它必须是可迭代的,产生Unicode字符串,所以我传递它应该没问题,不应该吗?
What am I doing wrong? 我究竟做错了什么?
TarFile.extractfile(member)
returns a file opened in binary mode. TarFile.extractfile(member)
返回以二进制模式打开的文件 。 The equivalent for read_file
is a file opened in text mode. read_file
的等效read_file
是在文本模式下打开的文件。 As such, the two do not match. 因此,两者不匹配。
You can wrap your extracted file in a io.TextIOWrapper
or a generator that converts to unicode: 您可以将提取的文件包装在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")
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.