Yeah, that was basically my first thought, too. If the file is small enough to easily fit in memory, read it all into an array and then walk the array for each operation. If it's too big for that, then read through it once doing both operations as you go. Either way, you'll get better performance out of it, since disk access is almost always the slowest operation.