Created
October 30, 2023 14:21
-
-
Save haa-zee/89cfac0e23cf4cec6971caedf6328ce3 to your computer and use it in GitHub Desktop.
asyncio file read
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
async def read_lines(file_path, lines): | |
with open(file_path, 'r') as file: | |
return [await file.readline() for _ in range(lines)] | |
async def main(): | |
file_path = "jou.txt" | |
lines = [5, 10, 15] | |
tasks = [asyncio.create_task(read_lines(file_path, line)) for line in lines] | |
contents = await asyncio.gather(*tasks) | |
for i in range(len(lines)): | |
print(f'Line {lines[i]} of the file: {contents[i]}') | |
if __name__ == '__main__': | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment