【问题标题】:How could I asynchronously read a specific line of a file with trio我怎么能用三重奏异步读取文件的特定行
【发布时间】:2019-08-11 18:30:56
【问题描述】:

所以我想用 trio(异步)打开文件,然后由于文件相当大,读取其中的单个特定行

所以在“普通”同步 python 中,我会做这样的事情:

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

这将打印文件第二行的内容

现在的问题是,当使用 trio 的 open_file 方法时,enumerate(f) 返回错误: TypeError: 'AsyncIOWrapper' object is not iterable

并遵循文档:

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

将只返回 i 的行值,并且只返回行的空格

那么,如何使用 trio/asynchronoulsy 读取大文件的特定行而不丢失大量内存?

【问题讨论】:

    标签: python python-3.x asynchronous python-trio


    【解决方案1】:

    像这样构建一个异步枚举函数:

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

    那么您可以轻松地执行以下操作:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多