[Tutor] Fastest way to iterate through a file

Robert Hicks sigzero at gmail.com
Tue Jun 26 15:19:07 CEST 2007


Kent Johnson wrote:
> Robert Hicks wrote:
>> I have a script at work where I have a list of id numbers and I am doing a:
>>
>> for line in ehFile:
> 
> That is fine
> 
>>      for id in line:
> 
> I don't know what this is for - line is a string, iterating it will give 
> you every character is the line.
>> 	
>> I am then going through that file and finding the line the id is on and 
>> printing the next line out. It takes a few seconds to see the output to 
>> the screen (the Perl version whips by) which got me to thinking I could 
>> be doing it faster (as I want to move it from Perl to Python).
>>
>> If you need all the code I can post that tomorrow or I can try any ideas 
>> posted to this.
> 
> A bit more code would help.
> 

This is the loop code:

for line in f2:
     for id in idList:
         if id in line:
             print "%s: %s" % (id, f2.next())
             found = "%s: %s" % (id, f2.next())
             f3.write(found)


I have an list, idList[], that contains a list of id numbers. That code 
will loop the the f2 file and for lines that have an id on it it will 
print the "next" line (so I can see what it is doing) and write it to a 
file. I will turn off that screen print after I get it going the way I 
want it to.

Robert



More information about the Tutor mailing list