title: "TypeError: write() argument must be str, not bytes" when trying to write an ElementTree to an XML file
body: <p>I'm trying to write some XML as a byte string (to wit, a response from the Zillow API) to an XML file using the <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write" rel="nofollow noreferrer"><code>ElementTree.write</code></a> method. Here is an example of what I'm trying to do:</p>
  
  <pre><code>from xml.etree import ElementTree
  
  content = b'&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;Comps:comps xsi:schemaLocation="http://www.zillow.com/static/xsd/Comps.xsd https://www.zillowstatic.com/vstatic/b20c067/static/xsd/Comps.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:Comps="http://www.zillow.com/static/xsd/Comps.xsd"&gt;&lt;request&gt;&lt;zpid&gt;48789177&lt;/zpid&gt;&lt;count&gt;1&lt;/count&gt;&lt;/request&gt;&lt;message&gt;&lt;text&gt;Request successfully processed&lt;/text&gt;&lt;code&gt;0&lt;/code&gt;&lt;/message&gt;&lt;response&gt;&lt;properties&gt;&lt;principal&gt;&lt;zpid&gt;48789177&lt;/zpid&gt;&lt;links&gt;&lt;homedetails&gt;https://www.zillow.com/homedetails/1614-E-Columbia-St-Seattle-WA-98122/48789177_zpid/&lt;/homedetails&gt;&lt;graphsanddata&gt;http://www.zillow.com/homedetails/1614-E-Columbia-St-Seattle-WA-98122/48789177_zpid/#charts-and-data&lt;/graphsanddata&gt;&lt;mapthishome&gt;http://www.zillow.com/homes/48789177_zpid/&lt;/mapthishome&gt;&lt;comparables&gt;http://www.zillow.com/homes/comps/48789177_zpid/&lt;/comparables&gt;&lt;/links&gt;&lt;address&gt;&lt;street&gt;1614 E Columbia St&lt;/street&gt;&lt;zipcode&gt;98122&lt;/zipcode&gt;&lt;city&gt;SEATTLE&lt;/city&gt;&lt;state&gt;WA&lt;/state&gt;&lt;latitude&gt;47.609388&lt;/latitude&gt;&lt;longitude&gt;-122.310834&lt;/longitude&gt;&lt;/address&gt;&lt;taxAssessmentYear&gt;2016&lt;/taxAssessmentYear&gt;&lt;taxAssessment&gt;528000.0&lt;/taxAssessment&gt;&lt;yearBuilt&gt;1907&lt;/yearBuilt&gt;&lt;lotSizeSqFt&gt;2613&lt;/lotSizeSqFt&gt;&lt;finishedSqFt&gt;2430&lt;/finishedSqFt&gt;&lt;bathrooms&gt;2.0&lt;/bathrooms&gt;&lt;bedrooms&gt;4&lt;/bedrooms&gt;&lt;zestimate&gt;&lt;amount currency="USD"&gt;900186&lt;/amount&gt;&lt;last-updated&gt;04/13/2018&lt;/last-updated&gt;&lt;oneWeekChange deprecated="true"&gt;&lt;/oneWeekChange&gt;&lt;valueChange duration="30" currency="USD"&gt;112285&lt;/valueChange&gt;&lt;valuationRange&gt;&lt;low currency="USD"&gt;783162&lt;/low&gt;&lt;high currency="USD"&gt;1053218&lt;/high&gt;&lt;/valuationRange&gt;&lt;percentile&gt;90&lt;/percentile&gt;&lt;/zestimate&gt;&lt;localRealEstate&gt;&lt;region name="Minor" id="271921" type="neighborhood"&gt;&lt;zindexValue&gt;588,800&lt;/zindexValue&gt;&lt;links&gt;&lt;overview&gt;http://www.zillow.com/local-info/WA-Seattle/Minor/r_271921/&lt;/overview&gt;&lt;forSaleByOwner&gt;http://www.zillow.com/minor-seattle-wa/fsbo/&lt;/forSaleByOwner&gt;&lt;forSale&gt;http://www.zillow.com/minor-seattle-wa/&lt;/forSale&gt;&lt;/links&gt;&lt;/region&gt;&lt;/localRealEstate&gt;&lt;/principal&gt;&lt;comparables&gt;&lt;comp score="7.0"&gt;&lt;zpid&gt;89822967&lt;/zpid&gt;&lt;links&gt;&lt;homedetails&gt;https://www.zillow.com/homedetails/1711-E-Fir-St-Seattle-WA-98122/89822967_zpid/&lt;/homedetails&gt;&lt;graphsanddata&gt;http://www.zillow.com/homedetails/1711-E-Fir-St-Seattle-WA-98122/89822967_zpid/#charts-and-data&lt;/graphsanddata&gt;&lt;mapthishome&gt;http://www.zillow.com/homes/89822967_zpid/&lt;/mapthishome&gt;&lt;comparables&gt;http://www.zillow.com/homes/comps/89822967_zpid/&lt;/comparables&gt;&lt;/links&gt;&lt;address&gt;&lt;street&gt;1711 E Fir St&lt;/street&gt;&lt;zipcode&gt;98122&lt;/zipcode&gt;&lt;city&gt;SEATTLE&lt;/city&gt;&lt;state&gt;WA&lt;/state&gt;&lt;latitude&gt;47.602463&lt;/latitude&gt;&lt;longitude&gt;-122.309743&lt;/longitude&gt;&lt;/address&gt;&lt;taxAssessmentYear&gt;2016&lt;/taxAssessmentYear&gt;&lt;taxAssessment&gt;513000.0&lt;/taxAssessment&gt;&lt;yearBuilt&gt;2008&lt;/yearBuilt&gt;&lt;lotSizeSqFt&gt;1306&lt;/lotSizeSqFt&gt;&lt;finishedSqFt&gt;1490&lt;/finishedSqFt&gt;&lt;bathrooms&gt;3.0&lt;/bathrooms&gt;&lt;bedrooms&gt;3&lt;/bedrooms&gt;&lt;lastSoldDate&gt;03/15/2018&lt;/lastSoldDate&gt;&lt;lastSoldPrice currency="USD"&gt;783000&lt;/lastSoldPrice&gt;&lt;zestimate&gt;&lt;amount currency="USD"&gt;791686&lt;/amount&gt;&lt;last-updated&gt;04/13/2018&lt;/last-updated&gt;&lt;oneWeekChange deprecated="true"&gt;&lt;/oneWeekChange&gt;&lt;valueChange duration="30" currency="USD"&gt;-8370&lt;/valueChange&gt;&lt;valuationRange&gt;&lt;low currency="USD"&gt;752102&lt;/low&gt;&lt;high currency="USD"&gt;831270&lt;/high&gt;&lt;/valuationRange&gt;&lt;percentile&gt;87&lt;/percentile&gt;&lt;/zestimate&gt;&lt;localRealEstate&gt;&lt;region name="Minor" id="271921" type="neighborhood"&gt;&lt;zindexValue&gt;588,800&lt;/zindexValue&gt;&lt;links&gt;&lt;overview&gt;http://www.zillow.com/local-info/WA-Seattle/Minor/r_271921/&lt;/overview&gt;&lt;forSaleByOwner&gt;http://www.zillow.com/minor-seattle-wa/fsbo/&lt;/forSaleByOwner&gt;&lt;forSale&gt;http://www.zillow.com/minor-seattle-wa/&lt;/forSale&gt;&lt;/links&gt;&lt;/region&gt;&lt;/localRealEstate&gt;&lt;/comp&gt;&lt;/comparables&gt;&lt;/properties&gt;&lt;/response&gt;&lt;/Comps:comps&gt;&lt;!-- H:042  T:99ms  S:2011  R:Sun Apr 15 09:01:05 PDT 2018  B:5.0.53029.1-hotfix_ADAT-2519.69881bc~hotfix-platform-for-2018-04-11.319b04e --&gt;'
  root = ElementTree.fromstring(content)
  tree = ElementTree.ElementTree(root)
  
  with open(f"comparables.xml", 'w+') as fp:
      tree.write(fp)
  </code></pre>
  
  <p>However, if I run this (in iPython) I get a <code>TypeError</code>:</p>
  
  <pre><code>In [3]: exec(open('zillow_api.py').read())
  ---------------------------------------------------------------------------
  TypeError                                 Traceback (most recent call last)
  &lt;ipython-input-3-23b53830497c&gt; in &lt;module&gt;()
  ----&gt; 1 exec(open('zillow_api.py').read())
  
  &lt;string&gt; in &lt;module&gt;()
  
  /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/xml/etree/ElementTree.py in write(self, file_or_filename, encoding, xml_declaration, default_namespace, method, short_empty_elements)
      774                 serialize = _serialize[method]
      775                 serialize(write, self._root, qnames, namespaces,
  --&gt; 776                           short_empty_elements=short_empty_elements)
      777 
      778     def write_c14n(self, file):
  
  /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py in __exit__(self, type, value, traceback)
       86         if type is None:
       87             try:
  ---&gt; 88                 next(self.gen)
       89             except StopIteration:
       90                 return False
  
  /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/xml/etree/ElementTree.py in _get_writer(file_or_filename, encoding)
      833                 # destroyed
      834                 stack.callback(file.detach)
  --&gt; 835                 yield file.write
      836 
      837 def _namespaces(elem, default_namespace=None):
  
  /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py in __exit__(self, *exc_details)
      378                 # set-up context
      379                 fixed_ctx = exc_details[1].__context__
  --&gt; 380                 raise exc_details[1]
      381             except BaseException:
      382                 exc_details[1].__context__ = fixed_ctx
  
  /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py in __exit__(self, *exc_details)
      363             cb = self._exit_callbacks.pop()
      364             try:
  --&gt; 365                 if cb(*exc_details):
      366                     suppressed_exc = True
      367                     pending_raise = False
  
  /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py in _exit_wrapper(exc_type, exc, tb)
      312         """
      313         def _exit_wrapper(exc_type, exc, tb):
  --&gt; 314             callback(*args, **kwds)
      315         # We changed the signature, so using @wraps is not appropriate, but
      316         # setting __wrapped__ may still help with introspection
  
  TypeError: write() argument must be str, not bytes
  </code></pre>
  
  <p>Is what I'm passing in not a "file object opened for writing" as specified in the docs?</p>
  
  <p>I've tried following the solution in <a href="https://stackoverflow.com/questions/42480442/elementtree-typeerror-write-argument-must-be-str-not-bytes-in-python3">ElementTree TypeError &quot;write() argument must be str, not bytes&quot; in Python3</a>, but the <code>tostring</code> method appears to no longer be contained in the <code>xml.etree</code> module.</p>