如何显示文件中的数据?

时间:2014-02-01 18:47:30

标签: python python-3.x shelve

请帮助提供此文件数据。

代码:

import tkinter
import shelve

def fileOpen():
    print('start output dictonary "db"', end = '\n')
    try:  
        db = shelve.open('data', 'r')        
    except:
        print('invalid filename. try again')
    else:    
        for record in db:
            print(record, ':: ', end = '\n')
            print('\ttype:\t', db[record].type, end = '\n')
            print('\tnumber:\t', db[record].number, end = '\n')
            print('\tvideo:\t', db[record].video, end = '\n')
            print('\taudio:\t', db[record].audio, end = '\n')
            print('=================')
            db.close()

def recAction(event, id, **args):
    print('ID: ', id, end = '\n')
    for arg in args:
        print(arg, '---', args[arg], end = '\n')

    db = shelve.open('data')

    try:
        db[id] = args
    except:
        tkinter.messagebox.showerror("Error", "invalid record. try again")
    else:
        db.close()
        tkinter.messagebox.showinfo("Complete", "Record complete")

    print('OK. now output dictonary "db"')
    fileOpen()

root = tkinter.Tk()
button = tkinter.Button(root, text = 'Send', height = 20, width = 20, relief = 'raised', cursor = 'hand1', font = ('times', 14, 'bold'))
button.bind('<Button-1>', lambda event: recAction(event, '1', type = 'dvd', number = '13', video = 'srat wars', audio = 'soundtrack'))
button.pack()

root.mainloop()

这里的函数recAction()是对文件数据的写入数据。然后将函数fileOpen()输出到屏幕。问题是当输出数据时出现错误信息:

Exception in Tkinter callback Traceback (most recent call last):   File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
    return self.func(*args)   File "C:\Python33\projects\DVD_LIST\p3_dvd_list_shelve_3d_class_edit_menubar\q.py", line 40, in <lambda>
    button.bind('<Button-1>', lambda event: recAction(event, '1', type = 'dvd', number = '13', video = 'srat wars', audio = 'soundtrack'))   File "C:\Python33\projects\DVD_LIST\p3_dvd_list_shelve_3d_class_edit_menubar\q.py", line 36, in recAction
    fileOpen()   File "C:\Python33\projects\DVD_LIST\p3_dvd_list_shelve_3d_class_edit_menubar\q.py", line 13, in fileOpen
    print('\ttype:\t', db[record].type, end = '\n') AttributeError: 'dict' object has no attribute 'type'

1 个答案:

答案 0 :(得分:0)

for record in db循环中,您正在迭代字典。

可以更好地迭代字典。

for record_key, record_value in db.items():
    print(record_key, ':: ', end = '\n')
    print('\ttype:\t', record_value['type'], end = '\n')
    print('\tnumber:\t', record_value['number'], end = '\n')
    print('\tvideo:\t', record_value['video'], end = '\n')
    print('\taudio:\t', record_value['audio'], end = '\n')
    print('=================')

错误消息表明db[record]也是字典。