title: UnicodeDecodeError: 'ascii' codec can't decode byte in position : ordinal not in range(128)
body: <p>I have done a bit of research on this error and can't really get my head around what's going on. As far as I understand I am basically having problems because I am converting from one type of encoding to another.</p>
  
  <pre><code>def write_table_to_file(table, connection):
      db_table = io.StringIO()
      cur = connection.cursor()
      #pdb.set_trace()
      cur.copy_to(db_table, table)
      cur.close()
      return db_tabl
  </code></pre>
  
  <p>This is the method that is giving me head aches. The below error is output when I run this method</p>
  
  <pre><code>[u350932@config5290vm0 python3]$ python3 datamain.py 
  Traceback (most recent call last):
    File "datamain.py", line 48, in &lt;module&gt;
      sys.exit(main())
    File "datamain.py", line 40, in main
      t = write_table_to_file("cms_jobdef", con_tctmsv64)
    File "datamain.py", line 19, in write_table_to_file
      cur.copy_to(db_table, table)
  UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 40: ordinal not in range(128)
  </code></pre>
  
  <p>The client encoding on the database im retrieving the table from is</p>
  
  <pre><code>tctmsv64=&gt; SHOW CLIENT_ENCODING;
   client_encoding
  -----------------
   sql_ascii
  (1 row)
  </code></pre>
  
  <p>The database encoding is LATIN1</p>
  
  <p>The encoding for the database I am putting them onto is</p>
  
  <pre><code>S104838=# SHOW CLIENT_ENCODING;
   client_encoding
  -----------------
   WIN1252
  (1 row)
  </code></pre>
  
  <p>The database encoding is UTF8</p>
  
  <p>From the threads I have found they recommend to change the encoding </p>
  
  <pre><code>To correct your function, you'll have to know what encoding the byte
  string is in, and convert it to unicode using the decode() method,
  and compare that result to the unicode string.
  </code></pre>
  
  <p><a href="http://www.thecodingforums.com/threads/unicodedecodeerror-ascii-codec-cant-decode-byte-0xa0-in-position-10-ordinal-not-in-range-128.336691/" rel="noreferrer">http://www.thecodingforums.com/threads/unicodedecodeerror-ascii-codec-cant-decode-byte-0xa0-in-position-10-ordinal-not-in-range-128.336691/</a></p>
  
  <p>The problem is when I try and use the decode methods I get complaints that its not a file type. I have had a look at the python 3.4 methods for  class io.StringIO(initial_value='', newline='\n')¶ method but could not find anything on changing the encoding.</p>
  
  <p>I also found this page which outlined the problem but I couldn't figure out what I needed to do to solve it</p>
  
  <p><a href="https://wiki.python.org/moin/UnicodeDecodeError" rel="noreferrer">https://wiki.python.org/moin/UnicodeDecodeError</a></p>
  
  <p>Basically I'm quite confused as to what is going on and not sure how to fix it. Any help would be greatly appreciated. </p>
  
  <p>Cheers</p>