comparing elements of a list with a string

Steve Holden steve at holdenweb.com
Tue Sep 25 13:48:45 EDT 2007


Larry Bates wrote:
> Shriphani wrote:
>> Hello all,
>> I have a problem here. I have a list named list_of_files which
>> contains filenames with their timestamps attached to the name. If I
>> have a string "fstab", and I want to list out the files in whose names
>> the word fstab appears should I go about like this :
>>
>> def listAllbackups(file):
>>     list_of_files = os.listdir("/home/shriphani/backupdir")
>>     for element in list_of_files:
>>          if element.find(file) != -1:
>>              date = ###
>>              time = ####
>>               return (date, time)
>>
>> The major trouble is that the return statement causes it to exit after
>> attempt one. How do I use the yield statement here?
>>
>> Regards,
>> Shriphani Palakodety
>>
> 
> You should take a quick look at glob().  You may be able to use it to make life 
> a lot easier.  Here is how you would do it if all your backup files begin with
> fstab.
> 
> import glob
> list_of_backup_files=glob.glob('/home/shriphani/backupdir/glob*')
> 
> If "fstab" can appear anywhere in the filename, this might not work for you.
> 
I don't see why

list_of_backup_files=glob.glob('/home/shriphani/backupdir/*fstab*')

shouldn't work. However, t answer the OP's question about yield (which 
nobody seems to have done fully yet):

1. Rewrite the function to become a generator function:

def listAllbackups(file):
     list_of_files = os.listdir("/home/shriphani/backupdir")
     for element in list_of_files:
          if file in element: # tidied this up too
              date = 1 ###
              time = 2 ####
              yield (date, time)

2. Create a generator by calling the function:

list_of_backup_files = listAllbackups("fstab")

3. Use the generator in an iterative context:

for file in list_of_backup_files:
     # do something

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

Sorry, the dog ate my .sigline




More information about the Python-list mailing list