Skip to content

Files

Latest commit

5591099 · Jul 3, 2021

History

History
75 lines (49 loc) · 2.14 KB

fileio.rst

File metadata and controls

75 lines (49 loc) · 2.14 KB

Asynchronous file I/O support

.. py:currentmodule:: anyio

AnyIO provides asynchronous wrappers for blocking file operations. These wrappers run blocking operations in worker threads.

Example:

from anyio import open_file, run


async def main():
    async with await open_file('/some/path/somewhere') as f:
        contents = await f.read()
        print(contents)

run(main)

The wrappers also support asynchronous iteration of the file line by line, just as the standard file objects support synchronous iteration:

from anyio import open_file, run


async def main():
    async with await open_file('/some/path/somewhere') as f:
        async for line in f:
            print(line, end='')

run(main)
.. seealso:: :ref:`FileStreams`

Asynchronous path operations

AnyIO provides an asynchronous version of the :class:`pathlib.Path` class. It differs with the original in a number of ways:

For example, to create a file with binary content:

from anyio import Path, run


async def main():
    path = Path('/foo/bar')
    await path.write_bytes(b'hello, world')

run(main)

Asynchronously iterating a directory contents can be done as follows:

from anyio import Path, run


async def main():
    # Print the contents of every file (assumed to be text) in the directory /foo/bar
    dir_path = Path('/foo/bar')
    async for path in dir_path.iterdir():
        if await path.is_file():
            print(await path.read_text())
            print('---------------------')

run(main)