From cf596206b0781bba82e5a76e8cc998cadd4cedf3 Mon Sep 17 00:00:00 2001 From: Olivier Mangin Date: Thu, 13 Jul 2017 21:13:02 -0400 Subject: [PATCH] FIX: Encode unicode before writing to file in python2. This is necessary because _open returns a file descriptor in binary mode for python2. --- pubs/content.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/pubs/content.py b/pubs/content.py index ee5f2af..c529b77 100644 --- a/pubs/content.py +++ b/pubs/content.py @@ -94,7 +94,16 @@ def remove_file(filepath): def write_file(filepath, data, mode='w'): + """Write data to file. + + Data should be unicode except when binary mode is selected, + in which case data is expected to be binary. + """ check_directory(os.path.dirname(filepath)) + if 'b' not in mode and sys.version_info < (3,): + # _open returns in binary mode for python2 + # Data must be encoded + data = data.encode('utf-8') with _open(filepath, mode) as f: f.write(data)