list index()

Steve Holden steve at holdenweb.com
Thu Aug 30 14:00:15 EDT 2007


zzbbaadd at aol.com wrote:
>> How could it not be an exception, in the plain English sense of the
>> word? Most certainly you're asking for the index because you want to do
>> something with the index. If the item is not found, you have no index,
>> so that's a special case that must be handled separately. There is no
>> logical difference between handling that special case in an except
>> clause versus handling it with an if-branch.
> 
> In my case of have done os.listdir() on two directories. I want to see
> what files are in directory A that are not in directory B.
> I have used exceptions in other languages and only do so on logic that
> should never happen. In this case it is known that some of the files
> will not be in both lists. I just want to know which ones.
> 
And, as is so often the case, once the *real* problem is stated a more 
elegant solution become available - in this case, using sets.

afiles = set(os.listdir(dira))
bfiles = set(os.listdir(dirb))

for f in (afiles - bfiles):
   print "Not common:", f


You can also generate the files that are in one directory but ot the 
other with

(afiles | bfiles) - (afiles & bfiles)

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list