TypeError: expected a character buffer object (while writing dictionary keys to text file)
<p>Below code doesn't work:</p>

<pre><code>with open("testfile.txt",'w') as fw:
    for key in a:
        fw.write(a[key])
</code></pre>

<p>Below is the error:</p>

<pre><code>Traceback (most recent call last):
  File "&lt;stdin&gt;", line 3, in &lt;module&gt;
TypeError: expected a character buffer object`
</code></pre>

<p>Below code works:</p>

<pre><code>with open('myfile.txt', 'w') as f:
    for key, value in a.items():
        f.write('%s:%s\n' % (key, value))
</code></pre>

<p>Can someone help me understand what's wrong in first block?</p>

<p>As the error message says: you can write only a character buffer object to a file. For example a <code>string</code>. However the entries in your dictionary are <code>int</code>s - which aren't character buffer objects. So you have first to convert the values to a string and than write it to a file, for example this conversion can be done via <code>'%d\n' % a[key]</code> or <code>'{0]\n'.format(a[key])</code>.</p>

<p>You could actually could use <code>'%s\n' % a[key]</code> and it would also work even if elements in the dictionary aren't integers. <code>%s</code> in python means that the conversion is done using the <code>str()</code> function, which is different from the usage in C, because in C <code>%s</code> means the formating of a null terminated string of characters. You could observe this in your second program and the reason I first thought the elements in your dictionary are <code>string</code>s.</p>

python python-2.7 file dictionary