On 12/26/2013 08:13 PM, Daniele Zambelli wrote:
p.save('esagono')
[...]
il metodo viene eseguito sotto Python 2.7 funziona, qundo lo
eseguo sotto Python 3.3 ottengo:
Traceback (most recent call last):
...
gs.write(s)
TypeError: must be str, not bytes
Qualcuno saprebbe darmi qualche indicazione per risolvere il caso?
Ciao Daniele, il file e' aperto in modo testuale, mentre s e' una
stringa di byte. Questo in Python 3 da luogo ad un errore, perche'
caratteri Unicode e byte, ovviamente, non devono, e quindi non possono,
essere confusi:
>>> f = open('myfile', 'w').write(b'foooo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str, not bytes
Il letterale b'foooo' e' una stringa di byte in Python 3. Infatti in
Python 3 le stringhe possono essere di byte o di caratteri Unicode:
>>> s1 = 'ciao'
>>> s2 = b'ciao'
>>> type(s1), type(s2)
(<class 'str'>, <class 'bytes'>)
>>> len('è')
1
>>> [i for i in 'è']
['è']
Nel tuo codice non hai avuto problemi usando Python 2 perche' purtroppo
il problema sta a monte, nel senso che il problema e' Python 2, dove il
tipo str crea una sorta di istanza promiscua di byte e testo:
>>> s = 'è'
>>> len(s)
2
>>> s
'\xc3\xa8'
Per creare una stringa di testo in Python 2 si usa il tipo unicode:
>>> s = unicode('è', encoding='utf-8')
>>> len(s)
1
Ciao, Marco
--
Marco Buttu
INAF-Osservatorio Astronomico di Cagliari
Via della Scienza n. 5, 09047 Selargius (CA)
Phone: 070 711 80 217
Email: mbu...@oa-cagliari.inaf.it
_______________________________________________
Python mailing list
Python@lists.python.it
http://lists.python.it/mailman/listinfo/python