0

I recently upgrading from python 2 to python 3. I have a code that queries a database via pyodbc.

Now when I output the results of these queries my files add b before each header, and quotes '' around each header. i.e. b'Header_Name', b'Header_Name2'

Does anyone know why this is? I thought it may be the open function w+, I have tried this with w here with the same error.

output_file = open(working_dir + "E"+str(s)+".txt", "w+")
cursor.execute(sql_string)

headers = []
col_count = 0
for col in cursor.description:
    print(str(col[0]) + '|',)
    headers.append(str(col[0]).encode("utf-8"))
    col_count = col_count + 1

output_file.write(','.join([str(v) for v in headers]) + "\n")

i = 0

for row in cursor:
    a=0
    values = []
    while a < col_count:
        values.append(str(row[a]))
        a=a+1

    output_file.write(','.join(values) + "\n")
    i = i + 1

output_file.close()
martineau
  • 119,623
  • 25
  • 170
  • 301
excelguy
  • 1,574
  • 6
  • 33
  • 67
  • its not originally my code actually, so i am not to familiar with `encode` or why they did it. – excelguy Aug 19 '19 at 19:17
  • Also, if you want to know a bit more about encoding / decoding and why you're getting this problem, check out [this link](https://realpython.com/python-encodings-guide/#encoding-and-decoding-in-python-3)! :) – Ravenlocke Aug 19 '19 at 19:20
  • If your code is *explicitly* encoding results as UTF-8 then that might go a long way to explain some of the confusion regarding [your earlier question](https://stackoverflow.com/q/57402005/2144390). – Gord Thompson Aug 19 '19 at 21:53

0 Answers0