我已经查看了堆栈溢出的答案,但它们似乎都是 str 或 list 或 int 不受支持缓冲区接口(interface),而我的问题是 dict 不受支持。我应该怎么办?字典不能复制到.bin 二进制文件吗?如果解决方案很复杂(或涉及模块),您能否向我解释一下该怎么做,因为我是编程新手。
我还可以补充一点,我不能使用外部模块(即 numPy 或 sciPy),因为我在工作计算机上没有安装模块的权限。我相信使用标准库可以解决这个问题,我只是不知道它是什么。
我正在使用 Python 3.4
#my code
def writeBinary():
myFile = open('books.bin','wb') #open binary file
book = {'Title': ' ', #create empty dictionary with keys and no values
'ISBN': ' ',
'Price': ' ',
'Year Of Publication': ' '}
end = False
while end != True:
option = input("Enter 'Y' to enter book details, or 'N' to quit: ")
if option == 'Y':
title = input("Enter the title of the book: ") #input data
book['Title'] = title #assign input data to dictionary keys
ISBN = input("Enter the ISBN of the book: ")
book['ISBN'] = ISBN
price = float(input("Enter the price of the book: £"))
book['Price'] = price
yearOfPublication = int(input("Enter the books year of publication: "))
book['Year Of Publication'] = yearOfPublication
myFile.write(book) #write dictionary to binary file
print(book) #to see the current contents of the dictionary
elif option == 'N':
print("Input terminated.")
end = True
else:
print("Invalid input. Please try again.")
myFile.close() #close binary file
writeBinary()
请您参考如下方法:
你不能在这样的文件上写字典。
你必须序列化字典,例如使用json(或pickle):
import json
myFile.write(json.dumps(book))
或直接(myFile 必须以w 模式打开,而不是wb):
json.dump(book,myFile)
然后使用
重新加载它with open('books.bin',"r") as myFile:
book = json.load(myFile)
json 比 pickle 有优势:序列化文件可以手动编辑,因为它是文本。但需要更多磁盘空间(除非压缩)。
