【发布时间】: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