0

I am using DataIku to read in a file, which is config.txt.

I am getting a "bytes" object back, and need to convert it into a string to send to configparser.

It looks a bit like this:

b"[email]\r\nsender = fred@somewhere.com.com\r\nreceiver = someoneelse@somewhere.com\r\nsubject = weekly email"

I am trying to convert it to a string:

data_string = str(data,"utf-8")

But this just gives me the same represenation, but without the "b" prefix.

"[email]\r\nsender = fred@somewhere.com.com\r\nreceiver = someoneelse@somewhere.com\r\nsubject = weekly email"

When I try to pass this into the read() method of configparser, it doesn't recognise the config as valid, as it can't find the sections [Email] for example.

import configparser
config = configparser.ConfigParser()
config.read(data_string)

input_file = config.get("email", "sender")
input_file

It fails miserably, likely because of the "\r\n" content of the string.

/usr/lib64/python3.6/configparser.py in _unify_values(self, section, vars)
   1139         except KeyError:
   1140             if section != self.default_section:
-> 1141                 raise NoSectionError(section)
   1142         # Update with the entry specific variables
   1143         vardict = {}

NoSectionError: No section: 'email'

How can I take a bytes object of a string, and just convert it into a normal string that configparser will accept?

I tried passing in the raw bytes object also into configparser.read(), which it supports, but this just killed the Kernel every time in the notebook.

Edit:

They closed this issue because apparently it has been answered 23 times before. None of those solutions work for me, decode() or str("utf-8") solve the problem. Why close the question down when my issue has not been resolved?

smackenzie
  • 2,880
  • 7
  • 46
  • 99
  • 1
    Your problem isn't converting the bytes object into a string. The problem is that you are using `config.read()` incorrectly. The argument of that method is a *filename*, not the string containing the configuration text. You want `config.read_string()` instead. – jjramsey May 11 '22 at 17:15
  • This works: https://stackoverflow.com/questions/21766451/how-to-read-config-from-string-or-list, as does read_string(). See, I knew they shouldn;t have closed the question. Thanks! – smackenzie May 11 '22 at 17:17
  • Your question was misleading, because you mistakenly indicated that it was about converting a bytes object to a string, so it looked very much like a question that had long since been asked and answered. Next time, when you ask a question, don't jump to conclusions about the source of your problem. – jjramsey May 11 '22 at 17:22

0 Answers0