Skip to content
This repository has been archived by the owner on May 15, 2020. It is now read-only.

Commit

Permalink
Merge pull request #7 from toddw-as/patch-1
Browse files Browse the repository at this point in the history
Allow an optional file encoding (codec).
  • Loading branch information
sashka committed Oct 15, 2014
2 parents 3f7a764 + becb445 commit 3f154ee
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
10 changes: 8 additions & 2 deletions atomicfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import errno
import os
import tempfile
import codecs


umask = os.umask(0)
Expand Down Expand Up @@ -46,11 +47,16 @@ class AtomicFile(object):
the temporary copy to the original name, making the changes visible.
If the object is destroyed without being closed, all your writes are
discarded.
If an ``encoding`` argument is specified, codecs.open will be called to open
the file in the wanted encoding.
"""
def __init__(self, name, mode="w+b", createmode=None):
def __init__(self, name, mode="w+b", createmode=None, encoding=None):
self.__name = name # permanent name
self._tempname = _maketemp(name, createmode=createmode)
self._fp = open(self._tempname, mode)
if encoding:
self._fp = codecs.open(self._tempname, mode, encoding)
else:
self._fp = open(self._tempname, mode)

# delegated methods
self.write = self._fp.write
Expand Down
21 changes: 21 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import os
import unittest
import codecs

from atomicfile import AtomicFile

Expand Down Expand Up @@ -73,6 +74,26 @@ def test_permissions(self):
finally:
os.remove(self.filename)

def test_encoding(self):
data = u"Unicode Capit\xe1n is written by AtomicFile.\n"
encoding = "utf-8"
af = AtomicFile(self.filename, "wb", encoding=encoding)
af.write(data)
af.close()

f = codecs.open(self.filename, "rb", encoding=encoding)
decoded_result = f.read()
f.close()
f = open(self.filename, "rb")
raw_result = f.read()
f.close()

try:
self.assertEqual(data, decoded_result)
self.assertEqual(data.encode(encoding), raw_result)
finally:
os.remove(self.filename)


if __name__ == "__main__":
unittest.main()

0 comments on commit 3f154ee

Please sign in to comment.