shelve.open()函数打开时的路径问题

今日自学看到了一个简单的数据库应用程序
中间利用了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下一切皆文件,有无后缀都可以

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值