Your code is functionally correct, but it could be more efficient with modifications, such as using a more appropriate data structure for the file content.
Instead of opening the file twice, consider reading it fully into memory and processing it in one go, which may improve performance.
Collection
[
|
...
]