今日自学看到了一个简单的数据库应用程序
中间利用了shelve这个模块,里面最让人关心的就是open函数,毕竟时打开文件并且读取
# -*- coding: utf-8 -*-
import shelve
def store_person(db):
# 让用户输入数据并将其存储到shelve对象当中
pid = input('Enter unique ID number:')
person = {}
person['name'] = input('Enter name:')
person['age'] = input('Enter age:')
person['phone'] = input('Enter phone number:')
db[pid] = person
def lookup_person(db):
# 让用户输入ID和所需的字段,并从shelve对象中获取相应的数据
pid = input('Enter ID number:')
field = input('What would you like to know?(name,age,phone)')
# strip移除字符串头尾指定的字符(默认为空格)或字符序列
field = field.strip().lower()
# capitalize将字符串的第一个字母变成大写,其他字母变小写
print(field.capitalize() + ':', db[pid][field])
def print_help():
print('The available commands are:')
print('store : Stores information about a person')
print('lookup : Looks up a person from ID number')
print('quit : Save changes and exit')
print('? : Prints this message')
def enter_command():
cmd = input('Enter command(? for help)')
cmd = cmd.strip().lower()
return cmd
def main():
database = shelve.open('F:\database')#windows下
database = shelve.open('databse.txt')#Linux下
try:
while True:
cmd = enter_command()
if cmd == 'store':
store_person(database)
elif cmd == 'lookup':
lookup_person(database)
elif cmd == '?':
print_help()
elif cmd == 'quit':
return
finally:
database.close()
main()
代码很简单,主要说明就是shelve.open()函数打开时的路径问题。
我在windows和linux下分别编译的
在window下,不需要加后缀名,windows下会自动补上,不必要提前创建文件,不过打开了也看不了,类似于编译文件。
在Linux下,不能提前创建文件,在编译过程中,这将自动创建成一个编译文件。而且Linux下一切皆文件,有无后缀都可以