Search code examples
pythonpython-3.xasynchronouspython-trio

How could I asynchronously read a specific line of a file with trio


So I'd like to open files with trio (asynchronously) and then as the file is rather large read a single specific line of it

So in "normal" synchronous python, I'd do something like this:

with open("text.txt") as f:
    for i, line in enumerate(f):
        if i == 3:
            print(line)

This would print the content of a file's second line

Now issue is, when using trio's open_file method, enumerate(f) returns the error: TypeError: 'AsyncIOWrapper' object is not iterable

And following the docs:

async with await trio.open_file("text.txt") as f:
    async for i, line in f:
        print(i)
        print(line)

will only return the line's value for i, and just whitespace for line

And so, how would one go to read a specific line of a large file without losing to much memory with trio/asynchronoulsy?


Solution

  • Building a async enumerate function as such:

    async def aenumerate(ait, start=0):
        i = start
        async for item in ait:
            yield i, item
            i += 1
    

    then you can easily do as follows:

    async with await trio.open_file("text.txt") as f:
        async for i, line in aenumerate(f):
            print(i)
            print(line)