2

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.

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?

What am I doing wrong?

Sardathrion - against SE abuse
  • 17,269
  • 27
  • 101
  • 156

1 Answers1

3

TarFile.extractfile(member) returns a file opened in binary mode. The equivalent for read_file is a file opened in text mode. As such, the two do not match.

You can wrap your extracted file in a io.TextIOWrapper or a generator that converts to 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")
)
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119