473,671 Members | 2,572 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pickled object, read and write..

Hi all.

I have to put together some code that reads high scores from a saved
file, then gives the user the opportunity to add their name and score
to the high scores list, which is then saved.

Trouble is, I can't tell the program to read a file that doesn't
exist, that generates an error.

So I must have a file created, problem HERE is everytime the program
is run, it will overwrite the current list of saved high scores.

Advice would be much appreciated.

Apr 22 '07 #1
3 1128
On Apr 22, 2:40 pm, "israph...@goog lemail.com"
<israph...@goog lemail.comwrote :
Hi all.

I have to put together some code that reads high scores from a saved
file, then gives the user the opportunity to add their name and score
to the high scores list, which is then saved.

Trouble is, I can't tell the program to read a file that doesn't
exist, that generates an error.

So I must have a file created, problem HERE is everytime the program
is run, it will overwrite the current list of saved high scores.

Advice would be much appreciated.
What did adding the standard try statement do?

Apr 22 '07 #2
hg
is*******@googl email.com wrote:
Hi all.

I have to put together some code that reads high scores from a saved
file, then gives the user the opportunity to add their name and score
to the high scores list, which is then saved.

Trouble is, I can't tell the program to read a file that doesn't
exist, that generates an error.

So I must have a file created, problem HERE is everytime the program
is run, it will overwrite the current list of saved high scores.

Advice would be much appreciated.

You can run this small script a few times to see that the file does not get
deleted

hg

import shelve
class Grades:
def __init__(self):
self.GRADES = 'GRADES'
self.m_gdb = shelve.open('MY GRADES.dat')

try:
self.m_grades = self.m_gdb[self.GRADES]
except:
self.m_grades = []
self.m_gdb[self.GRADES] = self.m_grades

self.m_gdb.clos e()

def Add(self, p_grade):
self.m_gdb = shelve.open('MY GRADES.dat')
self.m_grades.a ppend(p_grade)
self.m_gdb[self.GRADES] = self.m_grades
self.m_gdb.clos e()

def Grades(self):
return self.m_grades

l_o = Grades()
print l_o.Grades()
l_o.Add(10)
print l_o.Grades()
Apr 22 '07 #3
On Apr 22, 11:40 pm, "israph...@goog lemail.com"
<israph...@goog lemail.comwrote :
Hi all.

I have to put together some code that reads high scores from a saved
file, then gives the user the opportunity to add their name and score
to the high scores list, which is then saved.

Trouble is, I can't tell the program to read a file that doesn't
exist, that generates an error.

So I must have a file created, problem HERE is everytime the program
is run, it will overwrite the current list of saved high scores.

Advice would be much appreciated.
Try the following idiom:

try:
try:
fp = open("filename" , 'r+')
except IOError:
fp = open("filename" , 'w+')

fp.write(high_s core)
finally:
fp.close()
-Prateek

Apr 23 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
10137
by: simon place | last post by:
is the code below meant to produce rubbish?, i had expected an exception. f=file('readme.txt','w') f.write(' ') f.read() ( PythonWin 2.3 (#46, Jul 29 2003, 18:54:32) on win32. ) I got this while experimenting, trying to figure out the file objects modes,
1
2764
by: Maurizio Berlusconi | last post by:
Hi all I have (my mistake) overwritten the beginning of a file where a long dictionary was pickled with another (pickled and much smaller) dictionary. Since only 10% or so of the original and important data was overwritten, I would be happy if I could somehow recover at least the part that I can still see. The situation is now the following. If I open the file in vi I can see :
6
2664
by: BBM | last post by:
I have an object that has a fairly complex construction sequence, so I have written a dedicated "factory" class that invokes the constructor of my object class (which does nothing but instantiate the object and set default blank/null values), and then does all the Db access and number crunching to populate the new object. The factory returns the fully populated object to the caller. All the fields in the object are private, but have...
1
3211
by: DazedAndConfused | last post by:
Can you encrpt a serialized object? Or am I trying to do something that just doesn't work that way? I am trying to encrypt a serialized object. I can read and write the object to a file without a problem(IF I don't encrypt it). The encryption routine I am using works great when I am just reading in text and writing out encrypted data/Reading in encrpted data and writing out decrypted text.
0
1021
by: Bram Stolk | last post by:
Hi there, I'm transfering small pickled object over a socket. The performance I see is lower than expected. How fast should I be able to ping/pong small objects in python? I use a threaded SocketServer, telnetlib and pickle to test this, and I see that a 100 ping-pongs take 4 seconds or so, (over the localhost network).
4
3735
by: David Hirschfield | last post by:
I have a pair of programs which trade python data back and forth by pickling up lists of objects on one side (using pickle.HIGHEST_PROTOCOL), and sending that data over a TCP socket connection to the receiver, who unpickles the data and uses it. So far this has been working fine, but I now need a way of separating multiple chunks of pickled binary data in the stream being sent back and forth. Questions:
2
1177
by: krishnakant Mane | last post by:
hello all, I am trying a very complex kind of a task in a project. I have a knowledge management system where I need to store a lot of objects (pickled). I have to store mostly lists and dictionaries into a rdbms. mostly I will be using mysql. I want to know if there is any module that can help me store a pickled object inside a blob field instead of a file. I know that pickle.dump() can store an object into a file but I can't find a...
2
1453
by: krishnakant Mane | last post by:
hello, finally the errors for my sql query have changed so I have even changed the thread subject because I feel now that this is not doable in mysql and this seams to be a bug, ither in python or the MySQLdb module or perhaps both. my table is called testobj and the blob field is called obj. now following is my query with the cursor named CSRInsert. CSRInsert.execute("insert into testobj (obj) values (?);",(pickled_object)) the error...
2
2552
by: milan_sanremo | last post by:
I've read the library entry for pickle a couple of times, and I'm still not sure what data is maintained when an item is pickled and sent over a socket. Two importable modules: class envelope(): def __init__(self, rec, d): self.recipient = rec
0
8483
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8927
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8825
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8676
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7445
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6237
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5703
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2062
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1816
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.