[Tutor] any help with this piece of code

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu May 12 22:15:39 CEST 2005



On Thu, 12 May 2005, Richard gelling wrote:

> fileToSearchFor = raw_input( "Type in the file name you want to search
> for: ")
>
> if fileToSearchFor in fileList:
>     print "%s was found" % fileToSearchFor
> else:
>     print "%s was not found" % fileToSearchFor
>
> Could someone explain to me why this pice of code doesn't work, in that
> it works fine up until where I have commented , but when I come to
> search the list for a file name, even though I know the filename is in
> that particular directory, and is present in the list returned by
> 'fileList.append( files )' it always reports that the file is not found.

Hi Richard,


Ah.  TypeError.  *grin* At least, a conceptual one.


The code above accumulates the fileList with the following:

    fileList.append( files )


But the problem is that your fileList is a list of lists of file names.
What you really want to do is:

    fileList.extend( files )

to hold a flat list of file names in fileList.  The extend() method of a
list allows the list to absorb the elements of the other input list.



Concretely, your fileList probably looks something like this:

    [['hello.txt'], ['notes.txt', 'blah.txt']]

where you really want to have something like this instead:

    ['hello.txt', 'notes.txt', 'blah.txt']


Hope this helps!




More information about the Tutor mailing list