python如何用散列表实现简单数据库
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python如何用散列表实现简单数据库相关的知识,希望对你有一定的参考价值。
给你写了个小例子:# coding: UTF8
'''
A simple example for realize database functions with dictionary in Python.
Created on Jun 04, 2012
@author: P.J.
'''
class Database():
def __init__(self):
self.db =
def create_table(self, name):
self.db[name] = Table()
return self.db[name]
class Table():
def __init__(self):
self.tb =
self.row = 0
def insert(self, records):
self.row += 1
self.tb[self.row] = records
return self.row
def delete(self, row):
if self.tb.has_key(row):
del self.tb[row]
def update(self, row, records):
if self.tb.has_key(row):
self.tb[row] = records
def select(self, row=0):
if self.tb.has_key(row):
return self.tb[row]
else:
return []
db = Database()
tb = db.create_table("contact_book")
row = tb.insert(["Peter", "male", "Beijing", "186********"])
rs = tb.select(row)
tb.delete(row)
print rs 参考技术A python的字典就是用散列存储的吧
如何用python读取文本中指定行的内容
这里写个简单的,用readline即可实现,命令行带入参数1为读取的文件名,参数2为需要读取的行数。需要读取多行,你可以简单改改,例如参数带个列表,程序内用eval转化为数组之类的方法。
import sys
filename = sys.argv[1]
linenum = int(sys.argv[2])
with open(filename , 'r') as f:
line = f.readline()
n = 1
while line:
if linenum == n:
print line
break
else:
line = f.readline()
n += 1 参考技术A # readsomelines.py
# !/usr/bin/env python3
import sys
fname = 'aa.txt'
def main():
lines = [i for i in sys.argv[1:] if i.isdigit()]
with open(fname) as f:
s = f.read().split('\\n')
print('file name: , total: lines.'.format(fname, len(s)))
for i in lines:
index = int(i) - 1
content = s[index] if index < len(s) else ''
print('line : '.format(i, content))
main()$ python readsomelines.py 2 3
file name: aa.txt, total: 5 lines.
line 2: (comment line)
line 3: (atom symbol) 1 1 1
以上是关于python如何用散列表实现简单数据库的主要内容,如果未能解决你的问题,请参考以下文章