How to resolve "Typeerror: must be Unicode, not str" error in Python?

Asked

Viewed 1,026 times

5

When backing up my database on Sqlite3, the Python interpreter returns the following message:

Typeerror: must be Unicode, not str

on the line f.write("%s\n" % linha), I couldn’t find a solution regarding this mistake.

Follows the code:

#coding: utf-8
__author__ = 'Dener Carvalho'

import sqlite3
import io

#Conecta ao banco
conn = sqlite3.connect('clientes.db')

with io.open('clientes_dump.sql', 'w') as f:
    for linha in conn.iterdump():
        f.write("%s\n" % linha)

print 'Backup efetuado com sucesso.'
print 'Salvo como clientes_dump.sql'

conn.close()

2 answers

4


Severe in binary format and you won’t have a problem. It’s reckless to record a backup of a database as text:

#coding: utf-8
__author__ = 'Dener Carvalho'

import sqlite3
import io

#Conecta ao banco
conn = sqlite3.connect('clientes.db')

with io.open('clientes_dump.sql', 'wb') as f:
    for linha in conn.iterdump():
        f.write("%s\n" % linha)

print 'Backup efetuado com sucesso.'
print 'Salvo como clientes_dump.sql'

conn.close()

I put in the Github for future reference.

  • Thank you very much, it worked here. I don’t know why this error happened, I thought as text worked.

  • I am tempted to vote -1 for you nor comment to what the error means - although the answer is good, since the bank may have blobs. But I suggest reading http://local.joelonsoftware.com/wiki/O_M%C3%Adnimo_absoluto_que_todos_programadores_de_software_they need,_Absolutely,Positivamente_de_Saber_Sobre_Unicode_e_Conjuntos_de_Caracteres(Apologies!)

  • @jsbueno the question does not talk about it, it just wants the solution, you recognize yourself that the answer is good, then a negative would be pirraça, and any additional information about it will not solve anything, The solution is this, any one that involves Unicode will potentially create a problem. Look at my answers, when it’s pertinent, I explain, this is not the case.

1

In Python, str would be a binary type of data, while unicode is something more elaborate. You opened the file hoping to receive unicode and is trying to write str, therefore the mistake.

There are two options:

1. Open the file in binary mode

with io.open('clientes_dump.sql', 'wb') as f: # mude para 'wb'
    for linha in conn.iterdump():
        f.write("%s\n" % linha)

2. Convert str for unicode

with io.open('clientes_dump.sql', 'w') as f:
    for linha in conn.iterdump():
        f.write("%s\n" % unicode(linha))

See more about io here.

  • 1

    Thank you for the reply.

Browser other questions tagged

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