我只是想保存,文件没问题。但 db 是更好的选择。sqlite 是非常简单和好的数据库,它包含在 python 中。使用 sqlite 怎么样?
下面是示例代码。(对不起。快速而肮脏的代码)
#!usr/bin/python
import sqlite3
class People:
def __init__(self, fname=None, lname=None, age=None, gender=None):
self.fname = fname
self.lname = lname
self.age = age
self.gender = gender
self.save()
def save(self):
conn = sqlite3.connect('people.db')
c = conn.cursor()
c.execute("""create table if not exists
tbl_people(fname text, lname text,
age integer, gender text,
primary key (fname, lname) )""")
c.execute("""insert or replace into tbl_people(fname, lname, age, gender)
values ('%s', '%s', %d, '%s')
""" % (self.fname, self.lname, self.age, self.gender) )
conn.commit()
conn.close()
def display(self):
print self.fname
def search(fname, lname):
conn = sqlite3.connect('people.db')
c = conn.cursor()
c.execute("select * from tbl_people where fname='%s' and lname='%s'"%(fname,lname))
ppl = c.fetchone()
conn.close()
if ppl is not None:
return People(ppl[0], ppl[1], ppl[2], ppl[3])
else:
return None
ppl = People('John','Cooper',23,'Male')
ppl2 = People('Jane','Cooper',22,'Female')
ppl3 = search('John', 'Cooper')
ppl.display()
ppl3.display()