[英]Unable to write to binary file using pickle Python
因此,我在尝试将字典写入二进制文件而没有任何反应时遇到了这个问题。 很奇怪; 没有错误信息,什么都没有。 就像程序跳过了代码,特别是这段代码
with open("database.dat", "wb") as handle:
pickle.dump(d, handle)
handle.close()
我从这个database.dat文件中加载(如果存在)没有问题,但是如果该代码不存在,则此代码似乎不会创建新的二进制文件;如果存在,则该代码也不会覆盖该文件。 我从来没有遇到过这个问题,所以我很困惑。
为了给出适合的概念,请使用以下函数:
import pickle
def initialise_database(directory, file_name):
try:
with open("database.dat", "rb") as handle:
d = pickle.load(handle) # THIS WORKS PERFECTLY
handle.close()
return d
except FileNotFoundError:
return update_database(directory, file_name)
def update_database(directory, file_name):
import xlrd, os
# Change directory
os.chdir(directory)
try:
wb = xlrd.open_workbook(file_name)
sheet = wb.sheet_by_name("FUNDS")
rows, cols = sheet.nrows, sheet.ncols
d = {}
for i in range(rows - 1):
if sheet.cell_value(i + 1, 0) != "":
charity = cap(sheet.cell_value(i + 1, 0))
area_of_work = []
org = []
funding = 0
for x in range(cols):
if sheet.cell_value(0, x) == "Area of work":
if sheet.cell_value(i + 1, x) != "":
area_of_work.append(cap(sheet.cell_value(i + 1, x)))
else:
pass
elif sheet.cell_value(0, x) == "Organisation funded":
if sheet.cell_value(i + 1, x) != "":
org.append(cap(sheet.cell_value(i + 1, x)))
else:
pass
elif sheet.cell_value(0, x) == "How much funding provided":
funding = (str_to_int(sheet.cell_value(i + 1, x)))
if funding is False:
print("\nCharity " + str(sheet.cell_value(i + 1, 0)) + ", number " + str(i + 2) + " has funding of value: "+ str(funding) + ", which is not compatible. Please find it and fix it in the the excel file. Then try again")
return False
# Adds entry to dictionary
d[charity] = [area_of_work, org, funding]
else:
pass
# After the loop has finished, it should write the entire dictionary to a newly created file!
with open("database.dat", "wb") as handle:
pickle.dump(d, handle)
handle.close()
return d
except FileNotFoundError:
print("File could not be found.")
print("Program terminating.\n\nPress the enter key to exit.")
我看过其他问题,但似乎都没有碰到我在这里面临的问题。 任何有关如何解决它的帮助将不胜感激!
编辑:我还想在运行代码并执行时添加它
print(initialise_database( #my_directory, #my_file )
它确实打印出了我的数据库,这意味着正在调用update()函数,因为在任何地方都没有这样的database.dat文件
为了证明文件没有出现,这里是屏幕截图。 这是在运行full_script(获取此代码的位置)之后。
我会改变:
# Change directory
os.chdir(directory)
wb = xlrd.open_workbook(file_name)
成为:
import os.path
wb = xlrd.open_workbook(os.path.join(directory, file_name))
这样,“工作目录”将不会更改,并且文件将最终存放在您期望的位置。
稍微说明一下:每当open()
一个文件时(Python最终会调用该文件, xlrd
或任何其他本机代码也会xlrd
)。 不以/
开头的路径(在Windows中不是\\
)是相对于您的“当前工作目录”(CWD)还是仅相对于工作目录/文件夹。 您的CWD将继承自启动代码的程序(例如,shell或IDE),但您可以像使用os.chdir
一样以编程方式对其进行os.chdir
。
我通常不更改目录,因为它容易引起混乱(如您所经历的那样),并且仅使用到达正确位置的路径。 互联网上有很多更好的文档。 Microsoft有一个名为Naming Files,Paths和Namespaces的文档,其中包含所有详细信息,在Unix / Linux中通常更容易。 尝试搜索“相对VS绝对”路径名,并找出什么..
手段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.