Scrivere su file


In [2]:
with open(fname, "wb") as f:
    f.write(data)
    
with open(fname, "rb") as f:
    rows = f.readlines(data)



NameErrorTraceback (most recent call last)
<ipython-input-2-632ece8e3c3e> in <module>()
----> 1 with open(fname, "wb") as f:
      2     f.write(data)
      3 
      4 with open(fname, "rb") as f:
      5     rows = f.readlines(data)

NameError: name 'fname' is not defined

Unicode in breve

mettete sempre la u prima delle stringhe (u"")

v. unicode HowTO nelle references sotto


In [3]:
u"Papa" + u"aè"


Out[3]:
u'Papaa\xe8'

Leggere e scrivere files con contenuti Unicode


In [13]:
import codecs

with codecs.open('unicode.rst', encoding='utf-8', mode='w+') as f:
    f.write(u'\u4500 blah blah blah\n')
    f.seek(0)
    print repr(f.readline()[:1])

with codecs.open('unicode.rst', encoding='utf-8') as f:
    for line in f:
        print ("AAA", line)


u'\u4500'
('AAA', u'\u4500 blah blah blah\n')

In [ ]:
The most important tip is:

    Software should only work with Unicode strings internally, converting to a particular encoding on output.

Class e instance


In [25]:
class Greeter(object):

    def __init__(self, name, s="Ferroni"):
        self.name = name
        self._surname = s
        
    def hello(self):
        print("Hello {0.name}".format(self))

class SayGoodBye(object):
    def __init__(self, name, s="Ferroni"):
        self.name = name
        self._surname = s
        
    def bye(self):
        print("Bye {0.name}".format(self))
        
    def hello(self):
        print("Baaaaaaye {0.name}".format(self))

        
class HelloBye(SayGoodBye, Greeter):
    
    def __init__(self, *args, **kwargs):
        Greeter.__init__(self, *args, **kwargs)
        
    def hello(self):
        return Greeter.hello(self)

hb = HelloBye("Lucaaaa")
hb.bye()
hb.hello()


Bye Lucaaaa
Hello Lucaaaa

In [29]:
class Greeter(object):

    def __init__(self, name, s="Ferroni"):
        self.name = name
        self._surname = s
        
    def hello(self):
        print("Hello {0.name}".format(self))

        
class SayGoodByeFabriano(Greeter):
    
    def __init__(self, name="Luca"):
        super(SayGoodByeFabriano, self).__init__(name)
        self.city = "Fabriano"
        
    def bye(self):
        print("Bye from {0.city} {0.name}".format(self))
    
    def hello(self):
        super(SayGoodByeFabriano, self).hello()
        print("Hello from {0.city} {0.name}".format(self))
        
hb = SayGoodByeFabriano()
hb.bye()
hb.hello()


Bye from Fabriano Luca
Hello Luca
Hello from Fabriano Luca

In [53]:
import json
import csv

people_fname = r"c:\Users\gigi\lessons-python4beginners\src\gestionale\people_fixture.json"
with open(people_fname, "rb") as fpeople:
    PEOPLE = json.load(fpeople)
outfname = r"c:\Users\gigi\a.txt"

class DebugExporter(object):
    def do_export(self, f, rows):
        for row in rows:
            print("{}\n".format(row))
            
class Exporter(object):
    def do_export(self, f, rows):
        for row in rows:
            f.write("{}\n".format(row))

class JsonExporter(object):
    def do_export(self, f, rows):
        json.dump(rows, f, indent=2)


class CsvExporter(object):
    def do_export(self, f, rows):
        
        fieldnames = rows[0].keys()
        writer = csv.DictWriter(
            f, fieldnames = fieldnames, delimiter = ";")
        writer.writeheader()
        
        for row in rows:
            writer.writerow(row)

In [56]:
def apply_exportation(xp, fname, data):
    with open(fname, "wb") as f:
        xp.do_export(f, rows=data)

In [58]:
xp = JsonExporter()
apply_exportation(xp, outfname, data=PEOPLE)

xpcsv = CsvExporter()
csvfname = outfname.replace(".txt",".csv")
apply_exportation(xpcsv, csvfname, data=PEOPLE)

DB-API


In [ ]:
# [PEP 249](https://www.python.org/dev/peps/pep-0249/)
# v. gestionale/managers02/db.py

In [ ]:
class SqliteDBManager(object):
    
    def _do_export(self, rows):

        cu = self.conn.cursor()

        # KO: Never do this -- insecure!
        # KO: for row in rows:
        # KO:     c.execute("INSERT INTO people VALUES ('{name}','{city}','{salary}')".format(**row))

        # Do this instead
        for row in rows:
            t = (row["name"], row["city"], row["salary"])
            cu.execute('INSERT INTO people VALUES (?,?,?)', t)
        self.conn.commit()

Esercizio DB-API

  1. Fai in modo che il tuo gestionale: a. inizializzi un tabella PEOPLE su un database sqlite3 b. vi esporti i dati di PEOPLE c. inoltre possa registrare in un'altra tabella i dettagli "name" e "age" dei conigli posseduti
  2. BONUS: Importa un file json (o altro) all'avvio del tuo programma in modo da precaricare un set di dati in PEOPLE

In [32]:
import sqlite3 as db


def create_db(dsn):
    conn = db.connect(dsn)
    cu = conn.cursor()
    cu.execute("CREATE TABLE PEOPLE (name VARCHAR(32), city VARCHAR(32), salary INTEGER)")
    conn.close()
    
def save_db(fname, rows):
    conn = db.connect(fname)
    conn.row_factory = db.Row  # cursore indicizzato anche per chiave
        # è possibile definire una propria classe factory
        # https://docs.python.org/2.7/library/sqlite3.html?highlight=sqlite3#sqlite3.Connection.row_factory
    cu = conn.cursor()
    for row in rows:
        t = list(row[k] for k in ("name", "city", "salary"))
        cu.execute("INSERT INTO PEOPLE VALUES (?,?,?)", t)
    conn.commit()
    conn.close()
    
# create_db("mydatabase.db")

Feedback sono graditi

  • privati via luca@befair.it , cell: 3289639660
  • via telegram (sempre con il numero di cell)
  • se volete farli pubblici su www.befair.it

In [ ]:
phrase = "happy-python-hacking!"
the_end = u" ".join([s.capitalize() for s in phrase.split("-")])