title: Prepare the data for PostgreSQL COPY
body: <p>I have a list of objects which are scrapped content from a HTML pages and some of the values are HTML code which has special characters like quote and single quote <code>( like &lt;a href="http://.."&gt; )</code> and that needed to be escaped while preparing the CSV string but the inserted values are escaped so the HTML code is corrupted.</p>
  
  <p>My code :</p>
  
  <pre><code>import csv
  import subprocess
  
  insert_process = subprocess.Popen([
          'psql', 'dbname', '-U', 'user',
          '-c', '\COPY products(name,description,image) FROM STDIN',
          '--set=ON_ERROR_STOP=true'
          ], stdin=subprocess.PIPE
  
  
  /****
  Looping on the object and convert them to CSV raw with 'serialize_post_to_out_stream' function and append them to the stdin
  *****/
  
  
  
  # function to remove the new line and tab chars
  def clean_vars(var):
      return var.replace('\t', '').replace('\r', '').replace('\n', '')
  
  # function to convert the product object to csv raw
  def serialize_post_to_out_stream(product, out):
      writer = csv.writer(out, delimiter="\t",quotechar='\'', quoting=csv.QUOTE_MINIMAL)
      writer.writerow([product.name,clean_vars(product.description),product.image])
  
  # Closing the process to execute the COPY 
  insert_process.stdin.close()
  </code></pre>
  
  <p>Everything is working fine but the 'description' is corrupted HTML code like :</p>
  
  <pre><code>'&lt;li id="description" class="level-1"&gt;(DX-format): 5°20''&lt;/li&gt;      &lt;/li&gt;' 
  </code></pre>
  
  <p>There are some unwanted chars like the single quote in the beginning and the end of the value and if I removed :</p>
  
  <pre><code>quotechar='\''
  </code></pre>
  
  <p>Then every quote will be escaped with another quote.
  How to escape them for the CSV but inserting them cleaned in the DB.</p>