【问题标题】:Python 3.3 Pickle Errors for read/writePython 3.3 Pickle 读/写错误
【发布时间】:2014-05-10 23:05:39
【问题描述】:

我正在尝试编写一个显示菜单并允许用户写入文件、读取文件或退出的程序。该文件包含一个列表对象,因此我使用的是 .dat 文件。我已经阅读了这个站点上的 python 文档和大量的“pickle error”线程,但似乎无法理解为什么我会得到我得到的错误。我希望有任何见解!

write_to_file 函数出错:

integer is required

据我所知,我使用的是正确的 open 形式,这似乎是给其他用户带来此错误的原因,而且我在 Python 文档中找不到任何关于必需的内容pickle.dump 的整数参数(另外,我很确定我用来允许用户将数据输入文件的方法不正确,但我无法克服之前的泡菜错误。)

def write_to_file():
    s = open('studentInfo.dat')
    pickle.dump(info, s, 'wb')
    shelve.open(s)
    print(s)
    print("You may now add information to the file:")
    input(s[''])
    s.close()

read_file 函数出错:

io.UnsupportedOperation: write

我在这个函数中没有'w''wb' 参数,无论如何我希望它是一个只读操作。写入错误隐藏在哪里?

def read_file():
    f = open('studentInfo.dat', 'rb')
    pickle.dump(info, f)
    shelve.open(f, 'rb')
    print("Here is the student information: \n")
    print(f)
    f.close()

这是完整的代码:

#import necessary modules:
import pickle, shelve

# create list object
info = [[("student", "John"),("GPA","4.0"), ("ID", "01234")],
        [("student", "Harry"),("GPA","3.2"), ("ID", "03456")],
        [("student", "Melissa"),("GPA","1.8"), ("ID", "05678")],
        [("student", "Mary"),("GPA","3.5"), ("ID", "07899")]]

#Function Definitions
def write_to_file():
    s = open('studentInfo.dat')
    pickle.dump(info, s, 'wb')
    shelve.open(s)
    print(s)
    print("You may now add information to the file:")
    input(s[''])
    s.close()

def read_file():
    f = open('studentInfo.dat', 'rb')
    pickle.dump(info, f)
    shelve.open(f, 'rb')
    print("Here is the student information: \n")
    print(f)
    f.close()

#def main(): #while loop as program engine, constantly prompt user, display menu, etc.

menu = ("\n0 - Exit the Program",               #Exit
        "\n1 - Add student information",        #Write to file
        "\n2 - Print student information")  #Read file

print(menu)
menuchoice = int(input("Please enter a number that matches the menu option you want: "))
##writetofile = open("studentInfo.dat", "wb")
##printinfo = open("studentInfo.dat", "rb")

if menuchoice == 0:
    input("\nPress the 'enter' key to exit the program.")
elif menuchoice == 1:
    print("You may add a student, gpa, or student ID to the file")
    write_to_file()
elif menuchoice == 2:
    read_file()

【问题讨论】:

    标签: python python-3.x pickle


    【解决方案1】:

    你需要将mode参数传递给open()调用,传递给pickle.dump()

    s = open('studentInfo.dat', 'wb')
    pickle.dump(info, s)
    

    要从打开的文件加载,请使用pickle.load()

    f = open('studentInfo.dat', 'rb')
    info = pickle.load(f)
    

    您根本不需要shelve 模块并在这里调用。删除那些。

    您可能希望在此处将文件用作上下文管理器,自动关闭它们:

    with open('studentInfo.dat', 'wb') as outputfile:
        pickle.dump(info, outputfile)
    

    with open('studentInfo.dat', 'rb') as inputfile:
        info = pickle.load(inputfile)
    

    您不能在打开文件后只添加非结构化的附加信息;将新信息添加到info 之前info 酸洗到文件中:

    def write_to_file():
        # take input and add that to `info` here.
        # gather a name, GPA and ID into `new_name`, `new_gpa` and `new_id`
        info.append([("student", new_name),("GPA", new_gpa), ("ID", new_id)])
    
        with open('studentInfo.dat', 'wb') as outputfile:
            pickle.dump(info, outputfile)
    

    您的read_file() 函数可能应该返回读取信息,或者您应该将info 设为显式global

    def read_file():
        with open('studentInfo.dat', 'rb') as inputfile:
            info = pickle.load(inputfile)
        return info
    

    通过从函数返回,您可以将其分配回info 或打印:

    read_info = read_file()
    print("Here is the student information: \n")
    print(read_info)
    

    【讨论】:

    • 哇!感谢您的建议和示例。绝对修复了我的代码并教会了我一些东西。现在我只需要创建一个菜单功能,在用户输入或读取数据后会提示用户。干杯Martijn!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 2013-03-27
    • 1970-01-01
    • 2014-08-29
    相关资源
    最近更新 更多