title: Character detection in a text file in Python using the Universal Encoding Detector (chardet)
body: <p>I am trying to use the Universal Encoding Detector (chardet) in Python to detect the most probable character encoding in a text file ('infile') and use that in further processing.</p>
  
  <p>While chardet is designed primarily for detecting the character encoding of webpages, I have found an <a href="http://dbaktiar.wordpress.com/2009/09/15/chardet-python-library-determining-character-encoding-of-text/" rel="noreferrer">example</a> of it being used on individual text files.</p>
  
  <p>However, I cannot work out how to tell the script to set the most likely character encoding to the variable 'charenc' (which is used several times throughout the script).</p>
  
  <p>My code, based on a combination of the aforementioned example and chardet's own <a href="http://chardet.feedparser.org/docs/usage.html" rel="noreferrer">documentation</a> is as follows:</p>
  
  <pre><code>import chardet    
  rawdata=open(infile,"r").read()
  chardet.detect(rawdata)
  </code></pre>
  
  <p>Character detection is necessary as the script goes on to run the following (as well as several similar uses):</p>
  
  <pre><code>inF=open(infile,"rb")
  s=unicode(inF.read(),charenc)
  inF.close()
  </code></pre>
  
  <p>Any help would be greatly appreciated.</p>