title: Python Encoding\Decoding for writing to a text file
body: <p>I've honestly spent a lot of time on this, and it's slowly killing me.  I've stripped content from a PDF and stored it in an array.  Now I'm trying to pull it back out of the array and write it into a txt file.  However, I do not seem to be able to make it happen because of encoding issues.</p>
  
  <pre><code>allTheNTMs.append(contentRaw[s1:].encode("utf-8"))
  for a in range(len(allTheNTMs)):
          kmlDescription = allTheNTMs[a]
          print kmlDescription #this prints out fine
          outputFile.write(kmlDescription)
  </code></pre>
  
  <p>The error i'm getting is "unicodedecodeerror: ascii codec can't decode byte 0xc2 in position 213:ordinal not in range (128).  </p>
  
  <p>I'm just messing around now, but I've tried all kinds of ways to get this stuff to write out.</p>
  
  <pre><code>outputFile.write(kmlDescription).decode('utf-8')          
  </code></pre>
  
  <p>Please forgive me if this is basic, I'm still learning Python (2.7).</p>
  
  <p>Cheers!</p>
  
  <p>EDIT1:  Sample data looks something like the following:</p>
  
  <pre><code>Chart 3686 (plan, Morehead City) [ previous update 4997/11 ] NAD83 DATUM
  Insert the accompanying block, showing amendments to coastline,
  depths and dolphins, centred on: 34° 41´·19N., 76° 40´·43W.
  Delete R 34° 43´·16N., 76° 41´·64W.
  </code></pre>
  
  <p>When I add the print type(raw), I get  </p>
  
  <p>Edit 2:  When I just try to write the data, I receive the original error message (ascii codec can't decode byte...)</p>
  
  <p>I will check out the suggested thread and video.  Thanks folks!</p>
  
  <p>Edit 3:  I'm using Python 2.7</p>
  
  <p>Edit 4: agf hit the nail on the head in the comments below when (s)he noticed that I was double encoding.  I tried intentionally double encoding a string that had previously been working and produced the same error message that was originally thrown.  Something like:</p>
  
  <pre><code>text = "Here's a string, but imagine it has some weird symbols and whatnot in it - apparently latin-1"
  textEncoded = text.encode('utf-8')
  textEncodedX2 = textEncoded.encode('utf-8')
  outputfile.write(textEncoded) #Works!
  outputfile.write(textEncodedX2) #failed
  </code></pre>
  
  <p>Once I figured out I was trying to double encode, the solution was the following:</p>
  
  <pre><code>allTheNTMs.append(contentRaw[s1:].encode("utf-8"))
  for a in range(len(allTheNTMs)):
      kmlDescription = allTheNTMs[a]
      kmlDescriptionDecode = kmlDescription.decode("latin-1")
      outputFile.write(kmlDescriptionDecode)
  </code></pre>
  
  <p>It's working now, and I sure appreciate all of your help!!</p>