-2

I am trying to merge key-value pairs stored in multiple files. The files themselves are large so I want to do this in memory. The files are sorted, and contain 1 key-value pair per line, so normal k-way merge would work but I don't know how to iterate through the files together. Also in case I encounter multiple data points with the same keys, I want to combine them (add their values together) so the simple solution in Implementing an external merge sort does not work.I have tried using readlines to iterate over the files and storing indices, but readlines loads the entire file into memory so it does not acheive my need. As clarified by comments, the question boils down to reading consecutive lines from multiple files without using a for line in file loop.

6
  • 1
    readlines loads the entire file into memory so it does not acheive my need So read one line at a time. What is the difficulty? Commented Feb 18, 2024 at 17:27
  • 1
    Looks like you forgot to post the code you're struggling with MRE Commented Feb 18, 2024 at 17:28
  • @JohnGordon The problem being the way I know to iterate over IOstream is using a for loop, but I can't do that one at a time for multiple files like i need to for k-way merge Commented Feb 18, 2024 at 17:37
  • 1
    You can call file.readline() to read a single line. Is that the part you're missing? Commented Feb 18, 2024 at 17:40
  • you can have N files open at the time, put them in a list, and you can read a byte or line from any file you have open, be sure to close all the files you have opened Commented Feb 18, 2024 at 17:50

1 Answer 1

1

It seems your real question was "how do I arbitrarily read the next line from a file, without using a for line in file loop?"

The answer to that is file.readline().

Sign up to request clarification or add additional context in comments.

2 Comments

Or just next(file) which I would argue is more idiomatic
@juanpa.arrivillaga Or just use heapq.merge instead of trying to reimplement it, then they wouldn't even have this issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.