[Tutor] Dictionary File character reader
Dave Angel
davea at ieee.org
Tue May 10 11:55:31 CEST 2011
On 01/-10/-28163 02:59 PM, Clara Mintz wrote:
>
> Sorry I am completely new at python and don't understand why this function is returning an empty dictionary. I want it to take a list of files open them then return the number of characters as the value and the file name as the key.
> def fileLengths(files): d = {} files = [] for file in files: reader = open(file) for line in reader: char = sum(len(line)) d[file] = char reader.close return d
> Thank you sorry I don't understand what I am doing wrong.
> -Clara
The first thing you're doing is wordwrapping your program fragment. It
makes the code hard to read, and some aspects impossible, as we can't
tell what parts were indented by how much.
The second thing is clobbering your input parameter. files=[] will
obliterate whatever argument was passed to that function.
You will have more problems after that:
sum() won't work on an integer, so it's not clear why you're calling
len() on the line.
You're returning d from the function, but nothing in the function
ever inserts anything into it. So it will clearly be empty.
print is your friend. A couple of carefully placed print statements
would reveal these problems.
DaveA
More information about the Tutor
mailing list