Monday, July 20, 2009

Pickle Tutorial

What pickle does is take a python variable and serialize it (copy the binary from memory to the hard drive) this is the easiest method for backing up data for program use.

First step is to create a class to use the data. Even though Pickle can store all kinds of python basic variables, encapsulating backed up data within a class helps code readability.

class MrPickle():

Then you want to add a variable to it

class MrPickle():
data = []


Then you want to allow it to save itself to disk.

import Pickle

class MrPickle():
data = []

def save():
pickle.dump(self.data,open('mofo.dip','w'))

braking it down:
import Pickle = import the pickle library
pickle.dump() = save function
mrP.data = does not save full instance just basic variables
open() = opens a file for reading or writing. cannot append part files.
'mofo.dip' = file name
'w' = w for write r for read

Loading is more complex. Keep in mind if the file does not exist, open() when used in read mode will throw an exception.

import Pickle

class MrPickle():
data = []

def save():
pickle.dump(self.data,open('mofo.dip','w'))

def load():
try:
pData = pickle.load(open('mofo.dip','r'))
except:
self.save()

Explanation: first it tries to read the file and load it into self.data variable. If file does not exist it throws an exception and calls the class save function. Which then creates a file containing a blank array variable. Im asuming the file is saved to a source file named MaPickle.py

Now to use this class template:

pMan = MaPickle.MrPickle()
pMan.load()

First run creates a blank mofo.dip file. By manipulating the variable pMan.data then runing pMan.save(), any data in the variable will be re-loaded next time the program is run.

Thursday, April 2, 2009

File Sort Python

Reached beta!
https://sourceforge.net/projects/filesortpython/
Now for a quick description of what it does:

A Python script that allows you to move files form a Directory to sub-folders based on a Regular expression - useful for managing your monolithic download folder

I created the program because I always download all my sourceforge Apps, tv shows, and anime into one big download folder. After I get several hundred files filling several gigs, it gets hard to find what was recently downloaded. It also gets hard to find something I want to watch, as there are simply too many files to find the one I want. So to resolve the issue, I wrote this Python script to sort all the files based on a regular expression. Something I was unable to find in any other program. So I created File Sort Python, it still is missing some features like list sorting, priority change, among others. The file copy stage takes significantly longer than an alternative os specific cut and paste, but after a few minutes of building the database of patterns, it maintains the folder with far less effort.