__init__.py
branchstable
changeset 8131 a6654712ad50
parent 7879 9aae456abab5
child 8132 460472499d6d
--- a/__init__.py	Mon Dec 12 12:09:49 2011 +0100
+++ b/__init__.py	Mon Dec 19 19:03:27 2011 +0100
@@ -76,6 +76,49 @@
                "Binary objects must use raw strings, not %s" % data.__class__
         StringIO.write(self, data)
 
+    def to_file(self, filename):
+        """write a binary to disk
+
+        the writing is performed in a safe way for files stored on
+        Windows SMB shares
+        """
+        pos = self.tell()
+        with open(filename, 'wb') as fobj:
+            self.seek(0)
+            if sys.platform == 'win32':
+                while True:
+                    # the 16kB chunksize comes from the shutil module
+                    # in stdlib
+                    chunk = self.read(16*1024)
+                    if not chunk:
+                        break
+                    fobj.write(chunk)
+            else:
+                fobj.write(self.read())
+        self.seek(pos)
+
+    @staticmethod
+    def from_file(filename):
+        """read a file and returns its contents in a Binary
+
+        the reading is performed in a safe way for files stored on
+        Windows SMB shares
+        """
+        binary = Binary()
+        with open(filename, 'rb') as fobj:
+            if sys.platform == 'win32':
+                while True:
+                    # the 16kB chunksize comes from the shutil module
+                    # in stdlib
+                    chunk = fobj.read(16*1024)
+                    if not chunk:
+                        break
+                    binary.write(chunk)
+            else:
+                binary.write(fobj.read())
+        return binary
+
+
 # use this dictionary to rename entity types while keeping bw compat
 ETYPE_NAME_MAP = {}