[Tutor] List's name in a string

Jeff Shannon jeff at ccvcorp.com
Tue Sep 30 15:09:59 EDT 2003


Héctor Villafuerte D. wrote:
> 
> Jeff Shannon wrote:
> 
>> Héctor Villafuerte D. wrote:
>>
>> Okay, that seems pretty straightforward.  I'd do this following a 
>> rough skeleton something like this:
>>
>> outfile = file('LIST_proc', 'w')
>> for filename in LIST:
>>     infile = file(filename,'r')
>>     process_file(infile, outfile)
>>     infile.close()
>> outfile.close()
> 
> Ok, you're right.... I should have said that I have multiple LISTs and 
> that I want to do something like this:
>  >>> file_w = open(LIST.name() + '_proc', 'w')
> at least that's the basic idea.

Okay, you've got multiple lists that you want to apply the above 
treatment to.  You can keep those lists in a dictionary, like so:

list_dict = { 'LIST1': ['file1', 'file2', 'file3'],
               'LIST2': ['otherfile1', 'otherfile2'] }

And then you can iterate over the items in the dictionary:

for listname, filelist in list_dict.items():
     outfile_name = "%s_proc" % listname
     outfile = file(outfile_name, 'w')
     for filename in filelist:
         # ...

If you want to build the lists of filenames on the fly, that's fine, 
too.  Just assemble the list of files, generate a unique name, and 
plug them into the dictionary --

list_dict[name] = filelist

Or, say you have a long list of files that you're trying to categorize 
into different sublists.  You can use dict.get() to make this easier 
-- get() will return a default value if a key isn't found in the 
dictionary.

list_dict = {}
for filename in big_filelist:
     key = category(filename)
     existing = list_dict.get(key, [])
     existing.append(filename)
     list_dict[key] = existing

Hopefully this will give you some ideas on how to handle the specifics 
of your problem...

Jeff Shannon
Technician/Programmer
Credit International




More information about the Tutor mailing list