From 477a08c9e5418dfbe5b1446373d07e917e37bb68 2012-07-14 01:48:18 From: Dominik Dabrowski Date: 2012-07-14 01:48:18 Subject: [PATCH] Ensure encoding header gets written at start of file Check whether the file didn't exist beforehand or if we're not appending (in which case the file gets written anew anyways. --- diff --git a/IPython/core/magics/code.py b/IPython/core/magics/code.py index 3af9faa..f6726fe 100644 --- a/IPython/core/magics/code.py +++ b/IPython/core/magics/code.py @@ -81,7 +81,8 @@ class CodeMagics(Magics): fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) if not fname.endswith((u'.py',u'.ipy')): fname += ext - if os.path.isfile(fname) and not force and not append: + file_exists = os.path.isfile(fname) + if file_exists and not force and not append: try: overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n') except StdinNotImplementedError: @@ -97,7 +98,7 @@ class CodeMagics(Magics): return out = py3compat.cast_unicode(cmds) with io.open(fname, mode, encoding="utf-8") as f: - if not append: + if not file_exists or not append: f.write(u"# coding: utf-8\n") f.write(out) # make sure we end on a newline