我怎么能用 trio 异步读取文件的特定行
How could I asynchronously read a specific line of a file with trio
所以我想用 trio(异步)打开文件,然后由于文件相当大,所以我只读其中的一行
所以在 "normal" 同步 python 中,我会做这样的事情:
with open("text.txt") as f:
for i, line in enumerate(f):
if i == 3:
print(line)
这将打印文件第二行的内容
现在的问题是,当使用 trio 的 open_file 方法时,enumerate(f)
return 出现错误:
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)
只会 return i 的行值,而行
只会有空格
那么,trio/asynchronoulsy 如何在不丢失大量内存的情况下读取大文件的特定行?
构建异步枚举函数:
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)
所以我想用 trio(异步)打开文件,然后由于文件相当大,所以我只读其中的一行
所以在 "normal" 同步 python 中,我会做这样的事情:
with open("text.txt") as f:
for i, line in enumerate(f):
if i == 3:
print(line)
这将打印文件第二行的内容
现在的问题是,当使用 trio 的 open_file 方法时,enumerate(f)
return 出现错误:
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)
只会 return i 的行值,而行
只会有空格那么,trio/asynchronoulsy 如何在不丢失大量内存的情况下读取大文件的特定行?
构建异步枚举函数:
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)