[Tutor] question !
Brian van den Broek
broek at cc.umanitoba.ca
Tue Dec 20 22:18:46 CET 2005
Krava Magare said unto the world upon 2005-12-19 17:31:
> How can I remove and add record ( dictionary type) to a file. This is the program that I'm working on: the program should create a text file, print the contents of the text file, read the file after it's been created, add a record and print the contents of the file, remove a record(s) from the specified file, write it again, read it again, print the contens of the new file.
> Here is what I have so far:
I see that you did follow up to comp.lang.python with code and then
found your way here. Both are better than how you started :-)
But you really might want to read
<http://www.catb.org/~esr/faqs/smart-questions.html> to understand why
you've had no replies. This list (tutor) is far less strict about the
etiquette, but the advice is still good. (Keep in mind it is a busy
time of year, too :-)
Looking at what you have:
> import cPickle, shelve
> def write_file():
> CIT101 = ["Academic Computer Skills"]
> CIT234 = ["Decision Support Using Excel"]
> pickle_file = open("pickles1.dat","w")
> cPickle.dump(CIT101, pickle_file)
> cPickle.dump(CIT234, pickle_file)
> print "A file has been created and the required specifications have been added"
I suspect you don't really understand what pickle does. The task you
describe is to create text files, whereas pickle and cpickle are used
to save state of Python objects. They produce just barely human
readable files. For instance:
>>> pickled = open('pick', 'w')
>>> pickle.dump("This is a string", pickled)
>>> pickle.dump(["This is a list containing a string"], pickled)
produces this file:
S'This is a string'
S'This is a list containing a string'
where the strings are still there, but surrounded by 'gunk' that lets
the pickle modules reconstruct what was pickled.
In a more complicated case, pickled files are not at all readable. H
here is a pickle of an instance of a simple class:
Definitely not the sort of thing that is useful to a human!
I think you should consider switching tactics, and examine file() and
the read, readlines, write, and writelines methods of file objects.
More information about the Tutor