Skip to content

Instantly share code, notes, and snippets.

@haa-zee
Created October 30, 2023 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haa-zee/89cfac0e23cf4cec6971caedf6328ce3 to your computer and use it in GitHub Desktop.
Save haa-zee/89cfac0e23cf4cec6971caedf6328ce3 to your computer and use it in GitHub Desktop.
asyncio file read
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