git » el » commit 155cf8c

Use the tempfile module to create temporary files

author Alberto Bertogli
2010-06-24 23:18:32 UTC
committer Alberto Bertogli
2010-06-24 23:18:32 UTC
parent 89691603056acafd4cfd05f97d252bbd7491e364

Use the tempfile module to create temporary files

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>

el +7 -3

diff --git a/el b/el
index ed75d19..c3e29ed 100755
--- a/el
+++ b/el
@@ -6,6 +6,7 @@ import optparse
 import time
 import datetime
 import locale
+import tempfile
 import calendar
 import ConfigParser
 
@@ -62,7 +63,7 @@ class DB (object):
 			if not os.path.isdir(os.environ["HOME"] + "/.el/"):
 				os.mkdir(os.environ["HOME"] + "/.el/")
 			self.fname = os.environ["HOME"] + "/.el/events"
-		self.tmpfname = fname + ".tmp"
+		self.dirname = os.path.dirname(self.fname)
 		self.events = []
 		self.has_loaded = False
 
@@ -79,8 +80,11 @@ class DB (object):
 		self.load()
 		self.events.sort()
 		evts = [ e.to_dict() for e in self.events ]
-		json.dump(evts, open(self.tmpfname, 'w'), indent = 4)
-		os.rename(self.tmpfname, self.fname)
+		tmpfd, tmpfname = tempfile.mkstemp(dir = self.dirname)
+		tmpfd = os.fdopen(tmpfd, 'w')
+		json.dump(evts, tmpfd, indent = 4)
+		tmpfd.close()
+		os.rename(tmpfname, self.fname)
 
 	def append(self, evt):
 		self.events.append(evt)