How to fix error "TypeError: must be unicode, not str" in Python?

5

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

  

TypeError: must be unicode, not str

on line f.write("%s\n" % linha) , I could not find a solution for this error.

Follow 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()
    
asked by anonymous 25.08.2015 / 19:30

2 answers

4

Save to binary format and you will have no problems. It is rash to write 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()
    
25.08.2015 / 19:35
1

In Python, str would be a binary type of data, while unicode is something more elaborate. You opened the file expecting to receive unicode and are trying to write str , so the error.

There are two options:

1. Opening 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% with% to% with%

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

See more about str here .

    
25.08.2015 / 19:36