[PATCH 5 of 7] util: add readfile() & writefile() helper functions

Dan Villiom Podlaski Christiansen danchr at gmail.com
Tue Dec 7 10:26:43 CST 2010


# HG changeset patch
# User Dan Villiom Podlaski Christiansen <danchr at gmail.com>
# Date 1291739155 -3600
# Node ID 9aac41cf2a0c83501c7f9d0b1b912b64b834ddc6
# Parent  aead2861ecf9cb60f16b2a02bb8e5d217744c124
util: add readfile() & writefile() helper functions

These two functions allow quickly reading or writing a file, without
relying on reference counting to close the file handle afterwards.

diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -963,6 +963,20 @@ class opener(object):
             f.close()
             self._fixfilemode(dst)
 
+def readfile(path, size=-1):
+    fp = open(path)
+    try:
+        return fp.read(size)
+    finally:
+        fp.close()
+
+def writefile(path, mode, text):
+    fp = open(path, mode)
+    try:
+        fp.write(text)
+    finally:
+        fp.close()
+
 class chunkbuffer(object):
     """Allow arbitrary sized chunks of data to be efficiently read from an
     iterator over chunks of arbitrary size."""


More information about the Mercurial-devel mailing list