enigma2 20130314 (master) -> 20130424 (master)
[enigma2.git] / usr / lib / enigma2 / python / Tools / IO.py
1 from os import fchmod, fsync, path, rename, unlink
2 from tempfile import NamedTemporaryFile
3
4 def saveFile(filename, data, mode=0644):
5         tmpFilename = None
6         try:
7                 f = NamedTemporaryFile(prefix='.%s.' % path.basename(filename), dir=path.dirname(filename), delete=False)
8                 tmpFilename = f.name
9                 f.write(data)
10                 f.flush()
11                 fsync(f.fileno())
12                 fchmod(f.fileno(), mode)
13                 f.close()
14                 rename(tmpFilename, filename)
15         except Exception as e:
16                 print 'saveFile: failed to write to %s: %s' % (filename, e)
17                 if tmpFilename and path.exists(tmpFilename):
18                         unlink(tmpFilename)
19                 return False
20
21         return True