[Tutor] Dictionary File character reader

Noah Hall enalicho at gmail.com
Tue May 10 08:38:56 CEST 2011


On Tue, May 10, 2011 at 5:27 AM, Clara Mintz <jamani.sana at hotmail.com> 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 = []

Here's why. You take the name "files" and assign it to an empty list,
so you lose the "files" that you sent to the function.
>>> files = ["file_1.txt", "file_2.doc"]
>>> files
['file_1.txt', 'file_2.doc']
>>> files = []
>>> files
[]
You don't need that line at all, so remove it, and see what happens. :)

>     for file in files:
>         reader = open(file)
>         for line in reader:
>             char = sum(len(line))

As a side not, this doesn't need to be "sum" in this case - the len is
simply len, throwing away what it previously was. In fact, this
probably isn't what you want. At any one point, char is the length of
a single line, not the sum of every length of every line in the file.
What you want is something that takes the length of each line, and add
it to the sum. A simple way would be to do
>>>sum(len(line) for line in file)

>         d[file] = char
>         reader.close
>     return d
> Thank you sorry I don't understand what I am doing wrong.
> -Clara
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

Hope this helped.


More information about the Tutor mailing list