File support for asyncio

Overview

aiofiles: file support for asyncio

https://travis-ci.org/Tinche/aiofiles.svg?branch=master Supported Python versions

aiofiles is an Apache2 licensed library, written in Python, for handling local disk files in asyncio applications.

Ordinary local file IO is blocking, and cannot easily and portably made asynchronous. This means doing file IO may interfere with asyncio applications, which shouldn't block the executing thread. aiofiles helps with this by introducing asynchronous versions of files that support delegating operations to a separate thread pool.

async with aiofiles.open('filename', mode='r') as f:
    contents = await f.read()
print(contents)
'My file contents'

Asynchronous iteration is also supported.

async with aiofiles.open('filename') as f:
    async for line in f:
        ...

Features

  • a file API very similar to Python's standard, blocking API
  • support for buffered and unbuffered binary files, and buffered text files
  • support for async/await (PEP 492) constructs

Installation

To install aiofiles, simply:

$ pip install aiofiles

Usage

Files are opened using the aiofiles.open() coroutine, which in addition to mirroring the builtin open accepts optional loop and executor arguments. If loop is absent, the default loop will be used, as per the set asyncio policy. If executor is not specified, the default event loop executor will be used.

In case of success, an asynchronous file object is returned with an API identical to an ordinary file, except the following methods are coroutines and delegate to an executor:

  • close
  • flush
  • isatty
  • read
  • readall
  • read1
  • readinto
  • readline
  • readlines
  • seek
  • seekable
  • tell
  • truncate
  • writable
  • write
  • writelines

In case of failure, one of the usual exceptions will be raised.

The aiofiles.os module contains executor-enabled coroutine versions of several useful os functions that deal with files:

  • stat
  • sendfile
  • rename
  • remove
  • mkdir
  • rmdir

Writing tests for aiofiles

Real file IO can be mocked by patching aiofiles.threadpool.sync_open as desired. The return type also needs to be registered with the aiofiles.threadpool.wrap dispatcher:

aiofiles.threadpool.wrap.register(mock.MagicMock)(
    lambda *args, **kwargs: threadpool.AsyncBufferedIOBase(*args, **kwargs))

async def test_stuff():
    data = 'data'
    mock_file = mock.MagicMock()

    with mock.patch('aiofiles.threadpool.sync_open', return_value=mock_file) as mock_open:
        async with aiofiles.open('filename', 'w') as f:
            await f.write(data)

        mock_file.write.assert_called_once_with(data)

History

0.6.0 (2020-10-27)

  • aiofiles is now tested on ppc64le.
  • Added name and mode properties to async file objects. #82
  • Fixed a DeprecationWarning internally. #75
  • Python 3.9 support and tests.

0.5.0 (2020-04-12)

  • Python 3.8 support. Code base modernization (using async/await instead of asyncio.coroutine/yield from).
  • Added aiofiles.os.remove, aiofiles.os.rename, aiofiles.os.mkdir, aiofiles.os.rmdir. #62

0.4.0 (2018-08-11)

  • Python 3.7 support.
  • Removed Python 3.3/3.4 support. If you use these versions, stick to aiofiles 0.3.x.

0.3.2 (2017-09-23)

  • The LICENSE is now included in the sdist. #31

0.3.1 (2017-03-10)

  • Introduced a changelog.
  • aiofiles.os.sendfile will now work if the standard os module contains a sendfile function.

Contributing

Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

Owner
Tin Tvrtković
Tin Tvrtković
A tool written in python to generate basic repo files from github

A tool written in python to generate basic repo files from github

Riley 7 Dec 02, 2021
RMfuse provides access to your reMarkable Cloud files in the form of a FUSE filesystem

RMfuse provides access to your reMarkable Cloud files in the form of a FUSE filesystem. These files are exposed either in their original format, or as PDF files that contain your annotations. This le

Robert Schroll 82 Nov 24, 2022
Python interface for reading and appending tar files

Python interface for reading and appending tar files, while keeping a fast index for finding and reading files in the archive. This interface has been

Lawrence Livermore National Laboratory 1 Nov 12, 2021
pytiff is a lightweight library for reading chunks from a tiff file

pytiff is a lightweight library for reading chunks from a tiff file. While it supports other formats to some extend, it is focused on reading tiled greyscale/rgb images, that can also be bigtiffs. Wr

Big Data Analytics group 9 Mar 21, 2022
Ini adalah program python untuk mengubah background foto dalam 1 folder, tidak perlu satu satu

Myherokuapp my web drive You can see my web drive and can request film/Application do you want in here my blog you can visit my blog RemBg ini adalah

XnuxersXploitXen 13 Dec 01, 2022
Instant Fuzzy File Search for Alfred

List all the files inside a folder using fd, and instantly fuzzy-search through all of them using fzf, all from inside Alfred with a single keyword: fzf.

Mr. Pennyworth 37 Nov 30, 2022
Organizer is a python program that organizes your downloads folder

Organizer Organizer is a python program that organizes your downloads folder, it can run as a service and so will start along with the system, and the

Gustavo 2 Oct 18, 2021
A Python script to backup your favorite Discord gifs

About the project Discord recently felt like it would be a good idea to limit the favorites to 250, which made me lose most of my gifs... Luckily for

4 Aug 03, 2022
Get Your TXT File Length !.

TXTLen Get Your TXT File Length !. Hi 👋 , I'm Alireza A Python Developer Boy 🔭 I’m currently working on my C# projects 🌱 I’m currently Learning CSh

Alireza Hasanzadeh 1 Jan 06, 2022
Simple addon to create folder structures in blender.

BlenderCreateFolderStructure Simple Add-on to create a folder structure in Blender. Installation Download BlenderCreateFolderStructure.py Open Blender

Dominik Strasser 2 Feb 21, 2022
Some-tasks - Files for some of the tasks for the group sessions

Files for some of the tasks for the group sessions Here you can find some of the

<a href=[email protected] Computer Networks"> 0 Aug 25, 2022
Uncompress DEFLATE streams in pure Python

stream-inflate Uncompress DEFLATE streams in pure Python. Installation pip install stream-inflate Usage from stream_inflate import stream_inflate impo

Michal Charemza 7 Oct 13, 2022
Measure file similarity in a many-to-many fashion

Mesi Mesi is a tool to measure the similarity in a many-to-many fashion of long-form documents like Python source code or technical writing. The outpu

GatorEducator 3 Feb 02, 2022
Sheet Data Image/PDF-to-CSV Converter

Sheet Data Image/PDF-to-CSV Converter

Quy Truong 5 Nov 22, 2021
Pure Python tools for reading and writing all TIFF IFDs, sub-IFDs, and tags.

Tiff Tools Pure Python tools for reading and writing all TIFF IFDs, sub-IFDs, and tags. Developed by Kitware, Inc. with funding from The National Canc

Digital Slide Archive 32 Dec 14, 2022
Kartothek - a Python library to manage large amounts of tabular data in a blob store

Kartothek - a Python library to manage (create, read, update, delete) large amounts of tabular data in a blob store

15 Dec 25, 2022
This is just a GUI that detects your file's real extension using the filetype module.

Real-file.extnsn This is just a GUI that detects your file's real extension using the filetype module. Requirements Python 3.4 and above filetype modu

1 Aug 08, 2021
Publicly Open Amazon AWS S3 Bucket Viewer

S3Viewer Publicly open storage viewer (Amazon S3 Bucket, Azure Blob, FTP server, HTTP Index Of/) s3viewer is a free tool for security researchers that

Sharon Brizinov 377 Dec 02, 2022
Nmap XML output to CSV and HTTP/HTTPS URLS.

xml-to-csv-url Convert NMAP's XML output to CSV file and print URL addresses for HTTP/HTTPS ports. NOTE: OS Version Parsing is not working properly ye

1 Dec 21, 2021
LightCSV - This CSV reader is implemented in just pure Python.

LightCSV Simple light CSV reader This CSV reader is implemented in just pure Python. It allows to specify a separator, a quote char and column titles

Jose Rodriguez 6 Mar 05, 2022