TAGS :Viewed: 4 - Published at: a few seconds ago

[ Pickling a dict inside a PyQt app ]

I'm attempting to dump a pickle file in my PyQt app only its seems to be completely ignoring the statement.

import cPickle as pickle

class MyActions(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        #Create blank dictionary and save it.
        self.employee_dict = {}
        pickle.dump(self.employee_dict, open("pickle file", 'wb'))


        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'), self.emp_display )
        QtCore.QObject.connect(self.ui.pushButton_2, QtCore.SIGNAL('clicked()'), self.admin_display)

am i doing something wrong here or is pickle just not compatible with dumping dictionaries in side a PyQt gui.

Answer 1


Even though your question doesn't have enough information to go on, I'm willing to bet I know the answer.

You're creating a file called pickle file in whatever the current directory happens to be.

Then you're going and looking for the pickle file right next to the script, which is in general not going to be the current directory.

In the special case where you're running a script from the command line as ./foo.py or python ./foo.py, of course, the two happen to be the same. But when you double-click a PyQt app, it's… well, that depends on what platform you're on, and a variety of Explorer/Finder/Nautilus/etc. settings (either global, or per-app), but it's generally not going to be the same place the script is.


If you just want to force it to write the file next to the script (which is usually a bad idea), you can save the script directory at startup, like this:

import os
import sys

scriptdir = os.path.dirname(sys.argv[0])

Then, instead of writing to 'pickle file', you can write to os.path.join(scriptdir, 'pickle file').


However, a better solution is to use a platform-appropriate "app data" directory or "home" or "documents" directory (depending on whether you want the file to be visible to novice users); Qt has nice wrappers that make it easy to do that in the platform-appropriate way with platform-independent code.