[Tutor] a quick Q: how to use for loop to read a series of files with .doc end
Andreas Perstinger
andreas.perstinger at gmx.net
Thu Oct 6 07:39:17 CEST 2011
On 2011-10-06 05:46, lina wrote:
> On Thu, Oct 6, 2011 at 4:33 AM, Prasad, Ramit<ramit.prasad at jpmorgan.com>wrote:
>> Dictionaries {} are containers for key/value based pairs like { key :
>> value, another_key : value(can be same or repeated) }
>>
>> For example:
>> {'B': [0, 0, 0, 0, 0, 0], 'E': [2, 1, 4, 0, 1, 0]}
>> The keys here are 'B' and 'E'. The values here are [0, 0, 0, 0, 0, 0] (for
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>> key 'B') and [2, 1, 4, 0, 1, 0] (for key 'E')
>
> def writeonefiledata(outname,results):
> outfile = open(outname,"w")
> for key in results:
> return outfile.write(results[key])
>
> $ python3 counter-vertically-v2.py
> Traceback (most recent call last):
> File "counter-vertically-v2.py", line 43, in<module>
> dofiles(".")
> File "counter-vertically-v2.py", line 12, in dofiles
> processfile(filename)
> File "counter-vertically-v2.py", line 29, in processfile
> writeonefiledata(base+OUTFILEEXT,results)
> File "counter-vertically-v2.py", line 39, in writeonefiledata
> return outfile.write(results[key])
> TypeError: must be str, not list
^^^^^^^^^^^^^^^^^^^^^
The error message tells you, that "results[key]" is a list but "write"
just excepts a string. (see Ramit's explanation above).
You have to convert the list values to a string.
BTW: You shouldn't return the write operation because that will exit
your function after the first iteration.
> def writeonefiledata(outname,results):
> outfile = open(outname,"w")
> for key, value in results.iteritems():
> return outfile.write(key)
>
> $ python3 counter-vertically-v2.py
> Traceback (most recent call last):
> File "counter-vertically-v2.py", line 43, in<module>
> dofiles(".")
> File "counter-vertically-v2.py", line 12, in dofiles
> processfile(filename)
> File "counter-vertically-v2.py", line 29, in processfile
> writeonefiledata(base+OUTFILEEXT,results)
> File "counter-vertically-v2.py", line 38, in writeonefiledata
> for key, value in results.iteritems():
> AttributeError: 'dict' object has no attribute 'iteritems'
In Python 3 there is no "dict.iteritems()" any more:
http://docs.python.org/py3k/whatsnew/3.0.html#views-and-iterators-instead-of-lists
Use "dict.items()" instead
Bye, Andreas
More information about the Tutor
mailing list