简体   繁体   English

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

[英]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.

相关问题 Python3 类型错误:“值”必须是 str 或字节的实例,而不是元组 - Python3 TypeError: 'value' must be an instance of str or bytes, not a tuple ElementTree TypeError“write()参数必须是str,而不是Python3中的字节” - ElementTree TypeError “write() argument must be str, not bytes” in Python3 期望在python3中抛出错误为“必须在str中,而不是字节” - expect in python3 is throwing error as “must be in str , not bytes” 在 Python3 中解码字节字符串时出错 [TypeError: must be str, not bytes] - Error decoding byte string in Python3 [TypeError: must be str, not bytes] Python3 str(),字节和unicode - Python3 str(), bytes, and unicode TypeError:endswith first arg必须是str或str的元组,而不是布尔值 - TypeError: endswith first arg must be str or a tuple of str, not bool TypeError: endswith first arg 必须是 str 或 str 的元组,而不是 bool - TypeError: endswith first arg must be str or a tuple of str, not bool 使用Magpie + Tensorflow / Python3,“ TypeError:join()参数必须为str或字节,而不是'NoneType'” - “TypeError: join() argument must be str or bytes, not 'NoneType'” using Magpie+Tensorflow/Python3 write()参数必须为str,而不是字节数python - write() argument must be str, not bytes python Python - 类型错误:write() 参数必须是 str,而不是字节 - Python - TypeError: write() argument must be str, not bytes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM