ASCII codec can't encode character u'\u2013'
<p>I have a little Python code in Q_GIS which opens objects. The problem I have is that in the directory there is a character (underscore like character) that can not be encoded. The error is:</p>

<blockquote>
  <p>Traceback (most recent call last):   File "", line 1, in 
  UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in
  position 10: ordinal not in range(128)</p>
</blockquote>

<p>My little code is:</p>

<pre><code>from os import startfile; 
proj = QgsProject.instance(); 
UriFile = str(proj.fileName()); 
img = '[% "pad" %]'; 
Path = str(os.path.dirname(UriFile)); 
startfile(Path+img)
</code></pre>

<p>Because of my little programming skills, I ask you to help me add some code in this little code to overcome the problem.</p>

<p>I assume:</p>

<ul>
<li>you are using a Python2 version</li>
<li><code>QgsProject.instance().fileName()</code> is a unicode string containing a EN-DASH (Unicode char U+2013: &#8211;) this looks like a normal dash (Unicode char U+2D: -) but does not exists in ASCII nor in any common 8bits character set.</li>
</ul>

<p>The error is then normal: in Python2 the conversion of an unicode string to a plain 8bits string uses the ASCII character set.</p>

<p>Workaround:<br>
You can use an explicit encoding asking to use a <em>replace</em> character for unmapped ones:</p>

<pre><code>UriFile = proj.fileName().encode('ascii', 'replace')
</code></pre>

<p>at least you will see where the offending characters occurs.</p>

<p>Solution:</p>

<p>You should either use full unicode processing (and use Python3) or make sure that all string processed are representable in you current character set (often latin1)</p>

<p>Alternatively, if it make sense in your use case, you could try to use the UTF8 encoding which can successfully represent any UNICODE character in 1, 2 or 3 bytes:</p>

<pre><code>UriFile = proj.fileName().encode('utf8')
</code></pre>

python unicode