doc:appunti:prog:python_unicode
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionLast revisionBoth sides next revision | ||
doc:appunti:prog:python_unicode [2013/01/28 10:05] – [Nomi di file e directory] niccolo | doc:appunti:prog:python_unicode [2013/10/12 08:05] – [Input: lettura da database] niccolo | ||
---|---|---|---|
Line 5: | Line 5: | ||
Oppure queste slide: **[[http:// | Oppure queste slide: **[[http:// | ||
- | ===== Input: lettura da database ===== | + | ===== Input: lettura da database |
Si assume che nel database i campi testo siano codificati UTF-8. Sarebbe opportuno che il charset del database sia dichiarato UTF-8 in fase di creazione dello stesso; con PostgreSQL si tratta dell' | Si assume che nel database i campi testo siano codificati UTF-8. Sarebbe opportuno che il charset del database sia dichiarato UTF-8 in fase di creazione dello stesso; con PostgreSQL si tratta dell' | ||
Line 39: | Line 39: | ||
</ | </ | ||
+ | ===== Input/ | ||
+ | |||
+ | Con queste istruzioni si apre una connessione al database e ci si assicura che tutte le stringhe che vengono lette siano di **''< | ||
+ | |||
+ | <code python> | ||
+ | import psycopg2 | ||
+ | import psycopg2.extensions | ||
+ | psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) | ||
+ | psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY) | ||
+ | |||
+ | conn = psycopg2.connect(host = " | ||
+ | conn.set_client_encoding(" | ||
+ | curs = conn.cursor() | ||
+ | </ | ||
===== Input/ | ===== Input/ | ||
Line 77: | Line 91: | ||
<code python> | <code python> | ||
os.path.isfile(filename) | os.path.isfile(filename) | ||
+ | os.stat(filename) | ||
</ | </ | ||
Line 84: | Line 99: | ||
UnicodeEncodeError: | UnicodeEncodeError: | ||
</ | </ | ||
+ | |||
+ | La soluzione è codificare esplicitamente la stringa prima di passarla alla funzione: | ||
+ | |||
+ | <code python> | ||
+ | os.path.isfile(filename.encode(' | ||
+ | os.stat(filename.encode(' | ||
+ | </ | ||
+ |
doc/appunti/prog/python_unicode.txt · Last modified: 2015/07/17 09:50 by niccolo