Skip to content

Instantly share code, notes, and snippets.

@purarue
Last active August 5, 2019 00:15
Show Gist options
  • Save purarue/7ee7efacebd8d7da3ce77ec7f58c4a54 to your computer and use it in GitHub Desktop.
Save purarue/7ee7efacebd8d7da3ce77ec7f58c4a54 to your computer and use it in GitHub Desktop.
Read a file asynchronously using aiofiles, remove empty lines from a file
# python3 aiofiles_test.ty some_file_with_newlines
import sys
import asyncio
import aiofiles
async def read(filename):
async with aiofiles.open(filename, mode='r') as f:
return await f.read()
async def dump(filename, contents): # contents is an iterable
async with aiofiles.open(filename, mode='w') as old_f:
await old_f.write("\n".join(contents))
await old_f.flush()
filename = sys.argv[1]
loop = asyncio.get_event_loop()
contents = loop.run_until_complete(read(filename))
contents = list(filter(lambda x: bool(x.strip()), contents.splitlines()))
loop.run_until_complete(dump(filename, contents))
print(contents)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment