title: Rewrite file content with new content
body: <p>In a program - the program doesn't matter -, only the first lines, I open an empty file (named empty.txt).
  Then I define functions, but never use them on main ... so, I do not actually write anything.</p>
  <p>This the nearly complete code:</p>
  <pre><code>from os import chdir
   
  chdir('C:\\Users\\Julien\\Desktop\\PS BOT')
   
  fic=open('empty.txt','r+')
   
  def addtodic(txt):
      &quot;&quot;&quot;Messages de la forme !add id,message ; txt='id,message' &quot;&quot;&quot;
      fic.write(txt+'\n')
      fic.seek(0)
   
  def checkdic(txt):
      &quot;&quot;&quot;Messages de la forme !lien id ; txt='id' &quot;&quot;&quot;
      for i in fic.readlines().split('\n'):
          ind=i.index(',')
          if i[:ind]==txt:
              fic.seek(0)
              return i[ind+1:]
      fic.seek(0)
      return 'Not found'
  </code></pre>
  <p>Then I launch it, and using the console, I simply ask &quot;fic.write( 'tadam' )&quot;, like, to check if the writing works well before moving on.</p>
  <pre><code>%run &quot;C:/Users/Julien/Desktop/PS BOT/dic.py&quot;
   
  fic
  Out[8]: &lt;open file 'empty.txt', mode 'r+' at 0x0000000008D9ED20&gt;
   
  fic.write('tadam')
   
  fic.readline()
  Out[10]: 'os import chdir\n'
   
  fic.readline()
  Out[11]: &quot;chdir('C:\\\\Users\\\\Julien\\\\Desktop\\\\PS BOT')\n&quot;
   
  fic.readline()
  Out[12]: '\n'
   
  fic.readline()
  Out[13]: &quot;fic=open('empty.txt','r+')\n&quot;
   
  fic.readlines()
  Out[14]:
  ['\n',
   'def addtodic(txt):\n',
   '    &quot;&quot;&quot;Messages de la forme !add id,message ; txt=\'id,message\' &quot;&quot;&quot;\n',
   '    fic.seek(0)\n',
   &quot;    fic.write(txt)+'\\n'\n&quot;,
   '\n',
   'def checkdic(txt):\n',
   '    &quot;&quot;&quot;Messages de la forme !lien id ; txt=\'id\' &quot;&quot;&quot;\n',
   &quot;    for i in fic.readline().split('\\n'):\n&quot;,
   &quot;        ind=i.index(',')\n&quot;,
   '        if i[:ind]==txt:\n',
   '            fic.seek(0)\n',
   '            return i[ind+1:]\n',
   '    fic.seek(0)\n',
   &quot;    return 'Not found'\n&quot;,
   '    \n',
   'def removedic(txt):\n',
   '    &quot;&quot;&quot;Messages de la forme !remove id ; txt=\'id\' &quot;&quot;&quot;\n',
   '    check=True\n',
   '    while check:\n',
   '        i=fic.readline()\n',
   '        if i[:len(txt)]==txt:            \n',
   '            fic.seek(0)\n',
   '            return check\n',
   '#removedic fauxeturn check\r\n',
   &quot;#removedic faux    tmp_file = open(filename,'w')\n&quot;,
   '            tmp_file.write(data)\n',
   '            tmp_file.close()\n',
   '        return filename\n',
   '\n',
   '    # TODO:  This should be removed when Term is refactored.\n',
   '    def write(self,data):\n',
   '        &quot;&quot;&quot;Write a string to the default output&quot;&quot;&quot;\n',
   '        io.stdout.write(data)\n',
   '\n',
   '    # TODO:  This should be removed when Term is refactored.\n',
   '    def write_err(self,data):\n',
   '        &quot;&quot;&quot;Write a string to the default error output&quot;&quot;&quot;\n',
   '        io.stderr.write(data)\n',
   '\n',
   '    def ask_yes_no(self, prompt, default=None):\n',
   '        if self.quiet:\n',
   '            return True\n',
   '        return ask_yes_no(prompt,default)\n',
   '\n',
   '    def show_usage(self):\n',
   '        &quot;&quot;&quot;Show a usage message&quot;&quot;&quot;\n',
   '        page.page(IPython.core.usage.interactive_usage)\n',
   '\n',
   '    def extract_input_lines(self, range_str, raw=False):\n',
   '        &quot;&quot;&quot;Return as a string a set of input history slices.\n',
   '\n',
   '        Parameters\n',
   '        ----------\n',
   '        range_str : string\n',
   '            The set of slices is given as a string, like &quot;~5/6-~4/2 4:8 9&quot;,\n',
   '            since this function is for use by magic functions which get their\n',
   '            arguments as strings. The number before the / is the session\n',
   '            number: ~n goes n back from the current session.\n',
   '\n',
   '        Optional Parameters:\n',
   '          - raw(False): by default, the processed input is used.  If this is\n',
   '          true, the raw input history is used instead.\n',
   '\n',
   '        Note that slices can be called with two notations:\n',
   '\n',
   '        N:M -&gt; standard python form, means including items N...(M-1).\n',
   '\n',
   '        N-M -&gt; include items N..M (closed endpoint).&quot;&quot;&quot;\n',
   '        lines = self.history_manager.get_range_by_str(range_str, raw=raw)\n',
   '        return &quot;\\n&quot;.join(x for _, _, x in lines)\n',
   '\n',
   '    def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True):\n',
   '        &quot;&quot;&quot;Get a code string from history, file, url, or a string or macro.\n',
   '\n',
   '        This is mainly used by magic functions.\n',
   '\n',
   '        Parameters\n',
   '        ----------\n',
   '\n',
   '        target : str\n',
   '\n',
   '          A string specifying code to retrieve. This will be tried respectively\n',
   '          as: ranges of input history (see %history for syntax), url,\n',
   '          correspnding .py file, filename, or an expression evaluating to a\n',
   '          string or Macro in the user namespace.\n',
   '\n',
   '        raw : bool\n',
   '          If true (default), retrieve raw history. Has no effect on the other\n',
   '          retrieval mechanisms.\n',
   '\n',
   '        py_only : bool (default False)\n',
   '          Only try to fetch python code, do not try alternative methods to decode file\n',
   '          if unicode fails.\n',
   '\n',
   '        Returns\n',
   '        -------\n',
   '        A string of code.\n',
   '\n',
   '        ValueError is raised if nothing is found, and TypeError if it evaluates\n',
   '        to an object of another type. In each case, .args[0] is a printable\n',
   '        message.\n',
   '        &quot;&quot;&quot;\n',
   '        code = self.extract_input_lines(target, raw=raw)  # Grab history\n',
   '        if code:\n',
   '            return code\n',
   '        utarget = unquote_filename(target)\n',
   '        try:\n',
   &quot;            if utarget.startswith(('http://', 'https://')):\n&quot;,
   '                return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)\n',
   '        except UnicodeDecodeError:\n',
   '            if not py_only :\n',
   '                from urllib import urlopen  # Deferred import\n',
   '                response = urlopen(target)\n',
   &quot;                return response.read().decode('latin1')\n&quot;,
   '            raise ValueError((&quot;\'%s\' seem to be un']
  </code></pre>
  <p>KABOOM ! Has anybody an explanation ? By the way, I use Python 2.7 with Enthought Canopy.</p>