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:
Hi, 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"] <snip> > CIT234 = ["Decision Support Using Excel"] > pickle_file = open("pickles1.dat","w") > > cPickle.dump(CIT101, pickle_file) <snip> > cPickle.dump(CIT234, pickle_file) > print "A file has been created and the required specifications have > been added" > pickle_file.close <snip> 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) >>> pickled.close() produces this file: S'This is a string' p0 .(lp0 S'This is a list containing a string' p1 a. 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: ccopy_reg _reconstructor p0 (c__main__ A p1 c__builtin__ object p2 Ntp3 Rp4 (dp5 S'a' p6 I1 sS'c' p7 I3 sS'b' p8 I2 sb.ccopy_reg _reconstructor p0 (c__main__ A p1 c__builtin__ object p2 Ntp3 Rp4 (dp5 S'a' p6 I4 sS'c' p7 I6 sS'b' p8 I5 sb. 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. HTH, Brian vdB _______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
