问题描述
我有一个从腌制文件中导入数据的应用程序.在Windows上可以正常工作,但Mac和Linux的行为很奇怪.
I have an application that imports data from a pickled file. It works just fine in Windows but Mac and Linux behaviour is odd.
在OS X中,除非将文件类型设置为*.*,否则腌制的文件(文件扩展名".char")不可用.然后,如果我选择了扩展名为.char的文件,它将无法加载,并显示错误消息
In OS X, the pickled file (file extension ".char") is unavailable as a selection unless I set the file type to *.*. Then, if I select a file that has the .char extension, it won't load, giving the error
unpickle_file = cPickle.load(char_file)
ValueError:无法将字符串转换为浮点数
ValueError: could not convert string to float
但是,如果我创建的文件没有.char扩展名,则该文件将正常加载.
However, if I create a file that doesn't have the .char extension, that file will load up just fine.
在Linux中,当我使用文件打开"对话框时,无论它们是否具有文件扩展名,腌制的文件都不可见.但是,我可以在Nautilus或Dolphin下看到它们.但是,它们根本不存在于我的应用程序中.
In Linux, when I use the "file open" dialog, my pickled files aren't visible, whether or not they have a file extension. However, I can see them under Nautilus or Dolphin. They simply don't exist to my application though.
编辑:这是保存代码:
def createSaveFile(self):
"""Create the data files to be saved and save them.
Creates a tuple comprised of a dictionary of general character information
and the character's skills dictionary."""
if self.file_name:
self.save_data = ({'Name':self.charAttribs.name,
<snip>
self.charAttribs.char_skills_dict)
self.file = open(self.file_name, 'w')
cPickle.dump(self.save_data, self.file)
self.file.close()
这是公开代码:
def getCharFile(self, event): # wxGlade: CharSheet.<event_handler>
"""Retrieve pickled character file from disk."""
wildcard = "Character files (*.char) | *.char | All files (*.*) | *.*"
openDialog = wx.FileDialog(None, "Choose a character file", os.getcwd(),
"", wildcard, wx.OPEN | wx.CHANGE_DIR)
if openDialog.ShowModal() == wx.ID_OK:
self.path = openDialog.GetPath()
try:
char_file = open(self.path, "r")
unpickle_file = cPickle.load(char_file)
char_data, char_skills = unpickle_file
self.displayCharacter(char_data, char_skills)
except IOError:
self.importError = wx.MessageDialog(self,
"The character file is not available!",
"Character Import Error", wx.OK | wx.ICON_ERROR)
self.importError.ShowModal()
self.importError.Destroy()
openDialog.Destroy()
推荐答案
在写入和/或读取腌制数据时,可能没有以二进制模式打开文件.在这种情况下,将进行换行格式转换,这可能会破坏二进制数据.
Probably you didn't open the file in binary mode when writing and/or reading the pickled data. In this case newline format conversion will occur, which can break the binary data.
要以二进制模式打开文件,您必须在模式字符串中提供"b":
To open a file in binary mode you have to provide "b" as part of the mode string:
char_file = open('pickle.char', 'rb')
这篇关于腌制的文件不会在Mac/Linux上加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!