title: Escaping ampersand and other special characters in XML using Python
body: <p>I have to parse a large amount of XML files and write it to a text file. However, some of the XML files contain special/illegal characters. I have tried using different methods such as <a href="https://stackoverflow.com/questions/1546717/escaping-strings-for-use-in-xml">Escaping strings for use in XML</a>
  but I could not get it to work. I know 1 way to solve this is by editing the XML file itself, but there are thousands of files. </p>
  
  <pre><code>import os
  from xml.etree import ElementTree
  from xml.sax.saxutils import escape
  
  fileNum = 0;
  saveFile = open('NewYork_1.txt','w')
  
  for path, dirs, files in os.walk("NewYork_1"):
     for f in files:
        fileName = os.path.join(path, f)
        with open(fileName,'r', encoding='utf-8') as myFile:
          # print(myFile.read())
          if "&amp;" in myFile:
              myFile = myFile.replace("&amp;", "&amp;#38;") #This does not work.
  </code></pre>
  
  <p>Also, some of the XML files also have unicode in them. There are emojis.</p>
  
  <pre><code>&lt;Thread&gt;
     &lt;ThreadID&gt;&lt;/ThreadID&gt;
     &lt;Title&gt;&lt;/Title&gt;
     &lt;InitPost&gt;
        &lt;UserID&gt;&lt;/UserID&gt;
        &lt;Date&gt;&lt;/Date&gt;
        &lt;icontent&gt;&lt;/icontent&gt;
     &lt;/InitPost&gt;
     &lt;Post&gt;
        &lt;UserID&gt;&lt;/UserID&gt;
        &lt;Date&gt;&lt;/Date&gt;
        &lt;rcontent&gt;&lt;/rcontent&gt;
    &lt;/Post&gt;
  &lt;/Thread&gt;
  </code></pre>