Problems writing converted uuid from Binary(16) to csv file

Asked

Viewed 19 times

1

From a query in MySQL I receive lines with the field in the format binary(16) of MySQL. I do the conversion using lib uuid and try to insert into a file csv.

Does not write in format uuid in the archive csv, but in formats:

  • b'\x00\x03+\x9b.\xd25L\xac\xc2\x1a\xbe\x1b Xy',15
  • b"b'\\x00\\x03+\\x9b.\\xd25L\\xac\\xc2\\x1a\\xbe\\x1b Xy'"

Code:

with open('consumer_req.csv', 'w', newline='') as f:
    writer = csv.writer(f)

    headerFields = ['Consumer_id', 'Frequência']

    writer.writerow(headerFields)

    for row in results:
        bytearray_id, count = row

        byte_id = bytes(bytearray_id)

        print("\n", byte_id, " Type: ", type(byte_id))
        #Printa - b'\x00\x03+\x9b.\xd25L\xac\xc2\x1a\xbe\x1b Xy'  Type:  <class 'bytes'>

        consumer_id = uuid.UUID(bytes=byte_id)

        id_str = str(byte_id)

        print(id_str)
        #Printa - 00032b9b-2ed2-354c-acc2-1abe1b205879 -> O que eu quero no csv

        writer.writerow([id_str, str(count)])

How does csv come:

Consumer_id,Frequência
b'\x00\x03+\x9b.\xd25L\xac\xc2\x1a\xbe\x1b Xy',15
b'\x00\x03\xe5\xb9\x9f\xf3>]\x83\x86\xdex\xec\xf9\xf1=',6
b'\x00\x05\x8f\xa2\x9b|7\xa7\x8b\xf5J\xb8\xd9~\xf1\xcd',11
b'\x00\rx\xd6\xec\t?9\x86\xee\xfen2k\x9d\x04',7
"b""\x00't\x80\xeef5\xd8\x95\x10\x1d\x87~\xa6+b""",7
"b'\x00/\xca\xe1 G>\x9d\x96n1\xcd\xaf,<\xb1'",11
"b'\x003\xce\x1b\xe9\x017\xc7\x8a\xc3|g\x0f\xcf""\x9d'",7

1 answer

0


It is possible to use the package uuid to transform bytes into a string, or a representation of a UUID. Follows documentation.

Take the example:

import uuid
a = b'\x00\x03+\x9b.\xd25L\xac\xc2\x1a\xbe\x1b Xy' #utilizando o byte que forneceu na pergunta
c = uuid.UUID(bytes=a)
print(c)
#UUID('00032b9b-2ed2-354c-acc2-1abe1b205879')
# para imprimir a string basta fazer o cast para str.
str(c)
#'00032b9b-2ed2-354c-acc2-1abe1b205879'

To make the conversion I used the constructor that accepts bytes as parameter, so I can display the data in the proper representation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.