### Install Development Tools Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Install all necessary development tools, including linters and formatters, using the provided requirements file. ```bash pip install -r requirements.dev.txt ``` -------------------------------- ### Editable Install aiocsv Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Install aiocsv in editable mode for local development, which builds the C extension. This is necessary for running tests. ```bash pip install --editable . ``` -------------------------------- ### Async CSV Reading and Writing Example Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Demonstrates basic usage of aiocsv for reading and writing CSV and TSV files asynchronously. Includes examples for both list-based and dictionary-based readers/writers, with custom delimiters and quoting. ```python import asyncio import csv import aiofiles from aiocsv import AsyncReader, AsyncDictReader, AsyncWriter, AsyncDictWriter async def main(): # simple reading async with aiofiles.open("some_file.csv", mode="r", encoding="utf-8", newline="") as afp: async for row in AsyncReader(afp): print(row) # row is a list # dict reading, tab-separated async with aiofiles.open("some_other_file.tsv", mode="r", encoding="utf-8", newline="") as afp: async for row in AsyncDictReader(afp, delimiter="\t"): print(row) # row is a dict # simple writing, "unix"-dialect async with aiofiles.open("new_file.csv", mode="w", encoding="utf-8", newline="") as afp: writer = AsyncWriter(afp, dialect="unix") await writer.writerow(["name", "age"]) await writer.writerows([ ["John", 26], ["Sasha", 42], ["Hana", 37] ]) # dict writing, all quoted, "NULL" for missing fields async with aiofiles.open("new_file2.csv", mode="w", encoding="utf-8", newline="") as afp: writer = AsyncDictWriter(afp, ["name", "age"], restval="NULL", quoting=csv.QUOTE_ALL) await writer.writeheader() await writer.writerow({"name": "John", "age": 26}) await writer.writerows([ {"name": "Sasha", "age": 42}, {"name": "Hana"} ]) asyncio.run(main()) ``` -------------------------------- ### Run Tests Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Execute all project tests using pytest after installing the library. ```bash pytest ``` -------------------------------- ### Write CSV with Custom Dialect Parameters Source: https://context7.com/mkuranowski/aiocsv/llms.txt Configure AsyncWriter with custom dialect parameters such as `delimiter`, `quotechar`, and `quoting` to control the CSV output format. This example demonstrates writing a row with a semicolon in one of the fields using `csv.QUOTE_MINIMAL`. ```python import asyncio import csv import aiofiles from aiocsv import AsyncWriter # Custom dialect parameters async def write_with_custom_dialect(): async with aiofiles.open("output.csv", mode="w", encoding="utf-8", newline="") as afp: writer = AsyncWriter( afp, delimiter=";", quotechar='"', quoting=csv.QUOTE_MINIMAL ) await writer.writerow(["field1", "field with; semicolon", "field3"]) asyncio.run(write_with_custom_dialect()) ``` -------------------------------- ### Build aiocsv Wheel Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Use this command to create a wheel and source tarball for the aiocsv library. ```bash python -m build ``` -------------------------------- ### VS Code Recommended Settings Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Recommended VS Code settings for Python and C development within the aiocsv project, including format on save and testing configurations. ```json { "C_Cpp.codeAnalysis.clangTidy.enabled": true, "python.testing.pytestArgs": [ "." ], "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true, "[python]": { "editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.organizeImports": "always" } }, "[c]": { "editor.formatOnSave": true } } ``` -------------------------------- ### VS Code C/C++ Properties Configuration Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Manual configuration for VS Code's C/C++ extension to include Python headers, essential for C extension development. ```json { "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**", "/usr/include/python3.11" ], "defines": [], "compilerPath": "/usr/bin/clang", "cStandard": "c17", "cppStandard": "c++17", "intelliSenseMode": "linux-clang-x64" } ], "version": 4 } ``` -------------------------------- ### AsyncWriter Initialization Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Initializes an AsyncWriter for writing rows to an asynchronous CSV file. Additional keyword arguments are passed to the underlying csv.writer. ```python AsyncWriter( asyncfile: aiocsv.protocols.WithAsyncWrite, dialect: str | csv.Dialect | Type[csv.Dialect] = "excel", **csv_dialect_kwargs: Unpack[aiocsv.protocols.CsvDialectKwargs], ) ``` -------------------------------- ### AsyncDictWriter Initialization Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Initializes an AsyncDictWriter for writing dictionary-like rows to an asynchronous CSV file. Requires fieldnames and handles missing/extra keys based on `restval` and `extrasaction`. ```python AsyncDictWriter( asyncfile: aiocsv.protocols.WithAsyncWrite, fieldnames: Sequence[str], restval: Any = "", extrasaction: Literal["raise", "ignore"] = "raise", dialect: str | csv.Dialect | Type[csv.Dialect] = "excel", **csv_dialect_kwargs: Unpack[aiocsv.protocols.CsvDialectKwargs], ) ``` -------------------------------- ### AsyncDictReader Initialization Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Initializes an AsyncDictReader for asynchronous CSV file processing. All arguments mirror csv.DictReader. Use `await reader.get_fieldnames()` to retrieve fieldnames if they are not explicitly provided. ```python AsyncDictReader( asyncfile: aiocsv.protocols.WithAsyncRead, fieldnames: Optional[Sequence[str]] = None, restkey: Optional[str] = None, restval: Optional[str] = None, dialect: str | csv.Dialect | Type[csv.Dialect] = "excel", **csv_dialect_kwargs: Unpack[aiocsv.protocols.CsvDialectKwargs], ) ``` -------------------------------- ### Debug C Extension Build Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md For debugging the C part of aiocsv with debugging symbols, run this command and manually copy the shared object/DLL. ```bash python setup.py build --debug ``` -------------------------------- ### Use Built-in CSV Dialects with AsyncReader Source: https://context7.com/mkuranowski/aiocsv/llms.txt Read CSV files using predefined dialects like 'excel', 'excel-tab', or 'unix'. Each dialect specifies different delimiters, quoting rules, and line endings. Ensure the file is opened with the correct newline argument. ```python import asyncio import csv import aiofiles from aiocsv import AsyncReader, AsyncWriter, AsyncDictReader, AsyncDictWriter # Available built-in dialects: "excel", "excel-tab", "unix" async def use_dialects(): # Excel dialect (default) - comma-separated, CRLF line endings async with aiofiles.open("data.csv", mode="r", encoding="utf-8", newline="") as afp: async for row in AsyncReader(afp, dialect="excel"): print(row) # Excel-tab dialect - tab-separated async with aiofiles.open("data.tsv", mode="r", encoding="utf-8", newline="") as afp: async for row in AsyncReader(afp, dialect="excel-tab"): print(row) # Unix dialect - comma-separated, LF line endings, all fields quoted async with aiofiles.open("data.csv", mode="r", encoding="utf-8", newline="") as afp: async for row in AsyncReader(afp, dialect="unix"): print(row) asyncio.run(use_dialects()) ``` -------------------------------- ### Configure Custom CSV Dialect Parameters with AsyncReader Source: https://context7.com/mkuranowski/aiocsv/llms.txt Customize CSV parsing by providing specific parameters like `delimiter`, `quotechar`, `escapechar`, `quoting`, and `skipinitialspace` to AsyncReader. This allows handling non-standard CSV formats. Use `strict=True` to raise errors on malformed CSV data. ```python import asyncio import csv import aiofiles from aiocsv import AsyncReader, AsyncWriter, AsyncDictReader, AsyncDictWriter # Custom dialect parameters async def custom_dialect_params(): async with aiofiles.open("custom.csv", mode="r", encoding="utf-8", newline="") as afp: reader = AsyncReader( afp, delimiter="\t", # Field separator quotechar="'", # Character for quoting fields escapechar="\\", # Escape character doublequote=True, # Double quotes inside quoted fields skipinitialspace=True, # Skip whitespace after delimiter quoting=csv.QUOTE_ALL, # Quoting behavior strict=True # Raise errors on bad CSV ) async for row in reader: print(row) asyncio.run(custom_dialect_params()) ``` -------------------------------- ### AsyncDictWriter Methods Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Includes methods for writing a header row (`writeheader`), a single dictionary row (`writerow`), or multiple dictionary rows (`writerows`) to an asynchronous CSV file. ```python async writeheader(self) -> None: Writes header row to the specified file. async writerow(self, row: Mapping[str, Any]) -> None: Writes one row to the specified file. async writerows(self, rows: Iterable[Mapping[str, Any]]) -> None: Writes multiple rows to the specified file. ``` -------------------------------- ### Implement Custom Async File Objects for aiocsv Source: https://context7.com/mkuranowski/aiocsv/llms.txt Provides custom asynchronous reader and writer classes that implement the `WithAsyncRead` and `WithAsyncWrite` protocols, respectively. These can be used with `aiocsv` for processing CSV data from or to non-file sources. ```python import asyncio from typing import List from aiocsv import AsyncReader, AsyncWriter from aiocsv.protocols import WithAsyncRead, WithAsyncWrite # Custom async reader implementation class StringAsyncReader: """Async file-like object that reads from a string.""" def __init__(self, data: str): self.data = data self.pos = 0 async def read(self, size: int) -> str: chunk = self.data[self.pos:self.pos + size] self.pos += size return chunk # Custom async writer implementation class StringAsyncWriter: """Async file-like object that writes to an internal buffer.""" def __init__(self): self.buffer: List[str] = [] async def write(self, data: str) -> int: self.buffer.append(data) return len(data) def getvalue(self) -> str: return "".join(self.buffer) async def use_custom_file_objects(): # Read from string csv_data = "name,age\nAlice,28\nBob,35" reader_obj = StringAsyncReader(csv_data) async for row in AsyncReader(reader_obj): print(row) # ['name', 'age'], ['Alice', '28'], ['Bob', '35'] # Write to string buffer writer_obj = StringAsyncWriter() writer = AsyncWriter(writer_obj) await writer.writerow(["name", "age"]) await writer.writerow(["Charlie", "42"]) print(writer_obj.getvalue()) # "name,age\r\nCharlie,42\r\n" asyncio.run(use_custom_file_objects()) ``` -------------------------------- ### AsyncDictReader - Read CSV as Dictionaries Source: https://context7.com/mkuranowski/aiocsv/llms.txt AsyncDictReader iterates over CSV records as dictionaries, mapping column headers to values. It supports custom fieldnames, handling of extra/missing fields via `restkey` and `restval` parameters, and all standard CSV dialect options. ```APIDOC ## AsyncDictReader - Read CSV as Dictionaries ### Description Iterates over CSV records as dictionaries, mapping column headers to values. Supports custom fieldnames, `restkey`, `restval`, and standard CSV dialect options. ### Method Asynchronous iteration (e.g., `async for row in reader`) ### Endpoint N/A (Class usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import asyncio import aiofiles from aiocsv import AsyncDictReader async def read_csv_as_dicts(): async with aiofiles.open("users.csv", mode="r", encoding="utf-8", newline="") as afp: reader = AsyncDictReader(afp) fieldnames = await reader.get_fieldnames() print(f"Columns: {fieldnames}") async for row in reader: print(row) asyncio.run(read_csv_as_dicts()) ``` ### Response #### Success Response (200) Each iteration yields a dictionary representing a row, with keys as column headers. #### Response Example ```json { "name": "John", "email": "john@example.com", "age": "30" } ``` ``` -------------------------------- ### Handle Missing Fields with AsyncDictWriter Source: https://context7.com/mkuranowski/aiocsv/llms.txt Configure AsyncDictWriter with `restval` to provide default values for missing dictionary keys and `quoting=csv.QUOTE_ALL` to quote all fields. This is useful when input dictionaries may not contain all specified fieldnames. ```python import asyncio import csv import aiofiles from aiocsv import AsyncDictWriter async def write_with_missing_fields(): async with aiofiles.open("output.csv", mode="w", encoding="utf-8", newline="") as afp: writer = AsyncDictWriter( afp, fieldnames=["name", "age", "city"], restval="NULL", # Default value for missing keys quoting=csv.QUOTE_ALL # Quote all fields ) await writer.writeheader() await writer.writerows([ {"name": "John", "age": 26}, # city will be "NULL" {"name": "Sasha", "age": 42}, # city will be "NULL" {"name": "Hana", "age": 37, "city": "Tokyo"} ]) asyncio.run(write_with_missing_fields()) ``` -------------------------------- ### AsyncWriter Methods Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Provides methods for writing single rows (`writerow`) or multiple rows (`writerows`) to an asynchronous CSV file. ```python async writerow(self, row: Iterable[Any]) -> None: Writes one row to the specified file. async writerows(self, rows: Iterable[Iterable[Any]]) -> None: Writes multiple rows to the specified file. ``` -------------------------------- ### Read CSV as Dictionaries with AsyncDictReader Source: https://context7.com/mkuranowski/aiocsv/llms.txt AsyncDictReader iterates over CSV records as dictionaries, mapping column headers to values. Use `await reader.get_fieldnames()` to retrieve headers before iteration. It supports custom `fieldnames`, `restkey`, and `restval` for handling extra or missing columns, and standard CSV dialect options. ```python import asyncio import aiofiles from aiocsv import AsyncDictReader async def read_csv_as_dicts(): async with aiofiles.open("users.csv", mode="r", encoding="utf-8", newline="") as afp: reader = AsyncDictReader(afp) # Get fieldnames asynchronously (required before first iteration) fieldnames = await reader.get_fieldnames() print(f"Columns: {fieldnames}") # ['name', 'email', 'age'] # Iterate over rows as dictionaries async for row in reader: print(row) # {'name': 'John', 'email': 'john@example.com', 'age': '30'} # With custom fieldnames and missing value handling async def read_with_custom_fields(): async with aiofiles.open("data.csv", mode="r", encoding="utf-8", newline="") as afp: reader = AsyncDictReader( afp, fieldnames=["id", "name", "value"], # Custom headers restkey="extra", # Key for extra columns restval="N/A" # Value for missing columns ) async for row in reader: print(row) # Reading TSV files async def read_tsv(): async with aiofiles.open("data.tsv", mode="r", encoding="utf-8", newline="") as afp: async for row in AsyncDictReader(afp, delimiter="\t"): print(row) asyncio.run(read_csv_as_dicts()) ``` -------------------------------- ### aiocsv.AsyncDictReader Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Asynchronous dictionary reader for CSV files. Parses rows into dictionaries. ```APIDOC ## aiocsv.AsyncDictReader ### Description An object that iterates over records in the given asynchronous CSV file, returning each row as a dictionary. ### Parameters #### Constructor Parameters - **asyncfile** (aiocsv.protocols.WithAsyncRead) - Required - An object with an async `read(size: int)` coroutine. - **fieldnames** (List[str] | None) - Optional - A list of strings to use as field names. If None, the first row of the CSV will be used as field names. - **restval** (str) - Optional - Defaults to "". Value to use for fields that are missing in a row. - **restkey** (str) - Optional - Defaults to None. Key to use for the extra data read from a row, if any is available. - **dialect** (str | csv.Dialect | Type[csv.Dialect]) - Optional - Defaults to "excel". The CSV dialect to use. - **\*\*csv_dialect_kwargs** (aiocsv.protocols.CsvDialectKwargs) - Optional - Additional keyword arguments for CSV dialect parameters. ### Methods - `__aiter__(self) -> self` - `async __anext__(self) -> Dict[str, str]` - `async get_fieldnames(self) -> List[str] | None` ### Read-only properties - `dialect` (aiocsv.protocols.DialectLike): The dialect used when parsing. - `line_num` (int): The number of lines read from the source file. ### Request Example ```python import asyncio import aiofiles from aiocsv import AsyncDictReader async def read_dict_csv(): async with aiofiles.open("some_other_file.tsv", mode="r", encoding="utf-8", newline="") as afp: async for row in AsyncDictReader(afp, delimiter="\t"): print(row) asyncio.run(read_dict_csv()) ``` ``` -------------------------------- ### AsyncDictReader Fieldname Retrieval Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Demonstrates the difference in retrieving fieldnames between csv.DictReader and aiocsv.AsyncDictReader. For AsyncDictReader, fieldnames are not immediately available and must be awaited. ```python reader = csv.DictReader(some_file) reader.fieldnames # ["cells", "from", "the", "header"] areader = aiofiles.AsyncDictReader(same_file_but_async) areader.fieldnames # ⚠️ None await areader.get_fieldnames() # ["cells", "from", "the", "header"] ``` -------------------------------- ### AsyncReader - Read CSV as Lists Source: https://context7.com/mkuranowski/aiocsv/llms.txt AsyncReader iterates over records in an asynchronous CSV file, returning each row as a list of strings. It accepts any object with an async `read(size: int)` method and supports all standard CSV dialect parameters. ```APIDOC ## AsyncReader - Read CSV as Lists ### Description Iterates over records in an asynchronous CSV file, returning each row as a list of strings. Supports async `read(size: int)` method and standard CSV dialect parameters. ### Method Asynchronous iteration (e.g., `async for row in reader`) ### Endpoint N/A (Class usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import asyncio import aiofiles from aiocsv import AsyncReader async def read_csv_as_lists(): async with aiofiles.open("data.csv", mode="r", encoding="utf-8", newline="") as afp: reader = AsyncReader(afp) async for row in reader: print(row) print(f"Line number: {reader.line_num}") print(f"Delimiter: {reader.dialect.delimiter}") asyncio.run(read_csv_as_lists()) ``` ### Response #### Success Response (200) Each iteration yields a list of strings representing a row. #### Response Example ```json ["value1", "value2", "value3"] ``` ``` -------------------------------- ### AsyncWriter - Write CSV from Lists Source: https://context7.com/mkuranowski/aiocsv/llms.txt AsyncWriter writes CSV rows to an asynchronous file, where each row is a sequence of values. It supports all standard CSV dialects and formatting options through keyword arguments passed to the underlying `csv.writer`. ```APIDOC ## AsyncWriter - Write CSV from Lists ### Description Writes CSV rows to an asynchronous file. Each row is a sequence of values. Supports standard CSV dialects and formatting options. ### Method `writerow(row)`: Writes a single row. `writerows(rows)`: Writes multiple rows. ### Endpoint N/A (Class usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import asyncio import csv import aiofiles from aiocsv import AsyncWriter async def write_csv_from_lists(): async with aiofiles.open("output.csv", mode="w", encoding="utf-8", newline="") as afp: writer = AsyncWriter(afp) await writer.writerow(["name", "age", "city"]) await writer.writerows([ ["Alice", 28, "New York"], ["Bob", 35, "San Francisco"], ["Charlie", 42, "Chicago"] ]) asyncio.run(write_csv_from_lists()) ``` ### Response #### Success Response (200) CSV data is written to the specified asynchronous file. #### Response Example ```csv name,age,city Alice,28,New York Bob,35,San Francisco Charlie,42,Chicago ``` ``` -------------------------------- ### Read CSV as Lists with AsyncReader Source: https://context7.com/mkuranowski/aiocsv/llms.txt Use AsyncReader to iterate over records in an asynchronous CSV file, returning each row as a list of strings. It requires an async file-like object with a `read(size: int)` method and supports standard CSV dialect parameters. Access `reader.line_num` for the current line number and `reader.dialect` for dialect properties. ```python import asyncio import aiofiles from aiocsv import AsyncReader async def read_csv_as_lists(): async with aiofiles.open("data.csv", mode="r", encoding="utf-8", newline="") as afp: reader = AsyncReader(afp) # Iterate over all rows async for row in reader: print(row) # ['value1', 'value2', 'value3'] print(f"Line number: {reader.line_num}") # Access dialect properties print(f"Delimiter: {reader.dialect.delimiter}") # Using list comprehension async def read_all_rows(): async with aiofiles.open("data.csv", mode="r", encoding="utf-8", newline="") as afp: rows = [row async for row in AsyncReader(afp)] return rows asyncio.run(read_csv_as_lists()) ``` -------------------------------- ### Write CSV from Lists with AsyncWriter Source: https://context7.com/mkuranowski/aiocsv/llms.txt AsyncWriter writes CSV rows to an asynchronous file, where each row is a sequence of values. Use `await writer.writerow()` for a single row or `await writer.writerows()` for multiple rows. It supports standard CSV dialects and formatting options via keyword arguments. ```python import asyncio import csv import aiofiles from aiocsv import AsyncWriter async def write_csv_from_lists(): async with aiofiles.open("output.csv", mode="w", encoding="utf-8", newline="") as afp: writer = AsyncWriter(afp) # Write single row await writer.writerow(["name", "age", "city"]) # Write multiple rows at once await writer.writerows([ ["Alice", 28, "New York"], ["Bob", 35, "San Francisco"], ["Charlie", 42, "Chicago"] ]) # Using Unix dialect (quotes all fields, uses \n line endings) async def write_unix_style(): async with aiofiles.open("output.csv", mode="w", encoding="utf-8", newline="") as afp: writer = AsyncWriter(afp, dialect="unix") await writer.writerows([ ["Berlin", "Germany"], ["Paris", "France"], ["Rome", "Italy"] ]) ``` -------------------------------- ### aiocsv.AsyncDictWriter Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Asynchronous dictionary writer for CSV files. Writes dictionaries to a CSV. ```APIDOC ## aiocsv.AsyncDictWriter ### Description An object that writes dictionaries to the given asynchronous CSV file. ### Parameters #### Constructor Parameters - **asyncfile** (aiocsv.protocols.WithAsyncWrite) - Required - An object with an async `write(b: str)` coroutine. - **fieldnames** (List[str]) - Required - A list of strings specifying the order of fields in the output rows. - **restval** (str) - Optional - Defaults to "". Value to use for fields that are missing in a row. - **extrasaction** (str) - Optional - Defaults to "raise". Action to take when a dictionary contains a key not in `fieldnames`. Can be "raise" or "ignore". - **dialect** (str | csv.Dialect | Type[csv.Dialect]) - Optional - Defaults to "excel". The CSV dialect to use. - **\*\*csv_dialect_kwargs** (aiocsv.protocols.CsvDialectKwargs) - Optional - Additional keyword arguments for CSV dialect parameters. ### Methods - `writeheader(self) -> Awaitable[int]` - `writerow(self, rowdict: Dict[str, str]) -> Awaitable[int]` - `writerows(self, rowdicts: Iterable[Dict[str, str]]) -> Awaitable[int]` ### Read-only properties - `dialect` (aiocsv.protocols.DialectLike): The dialect used when writing. ### Request Example ```python import asyncio import csv import aiofiles from aiocsv import AsyncDictWriter async def write_dict_csv(): async with aiofiles.open("new_file2.csv", mode="w", encoding="utf-8", newline="") as afp: writer = AsyncDictWriter(afp, ["name", "age"], restval="NULL", quoting=csv.QUOTE_ALL) await writer.writeheader() await writer.writerow({"name": "John", "age": 26}) await writer.writerows([ {"name": "Sasha", "age": 42}, {"name": "Hana"} ]) asyncio.run(write_dict_csv()) ``` ``` -------------------------------- ### Write CSV from Dictionaries with AsyncDictWriter Source: https://context7.com/mkuranowski/aiocsv/llms.txt Use AsyncDictWriter to write rows from dictionaries. It handles writing the header and supports writing single or multiple rows. Ensure fieldnames are provided. ```python import asyncio import csv import aiofiles from aiocsv import AsyncDictWriter async def write_csv_from_dicts(): async with aiofiles.open("users.csv", mode="w", encoding="utf-8", newline="") as afp: fieldnames = ["name", "email", "age"] writer = AsyncDictWriter(afp, fieldnames) # Write header row await writer.writeheader() # Write single row await writer.writerow({"name": "Alice", "email": "alice@example.com", "age": 28}) # Write multiple rows await writer.writerows([ {"name": "Bob", "email": "bob@example.com", "age": 35}, {"name": "Charlie", "email": "charlie@example.com", "age": 42} ]) asyncio.run(write_csv_from_dicts()) ``` -------------------------------- ### aiocsv.AsyncDictReader Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md An object that iterates over records in an asynchronous CSV file, returning parsed rows as dictionaries. ```APIDOC ## AsyncDictReader ### Description An object that iterates over records in the given asynchronous CSV file. All arguments work exactly the same was as in csv.DictReader. Iterating over this object returns parsed CSV rows (`Dict[str, str]`). ### Parameters - **asyncfile** (aiocsv.protocols.WithAsyncRead) - Required - The asynchronous file object to read from. - **fieldnames** (Optional[Sequence[str]]) - Optional - A sequence of strings representing the header row. If None, the first row will be used as fieldnames. - **restkey** (Optional[str]) - Optional - If a row has more cells than the header, all remaining cells are stored under this key. - **restval** (Optional[str]) - Optional - If a row has less cells than the header, then missing keys will use this value. - **dialect** (str | csv.Dialect | Type[csv.Dialect]) - Optional - The CSV dialect to use. Defaults to "excel". - **csv_dialect_kwargs** (Unpack[aiocsv.protocols.CsvDialectKwargs]) - Optional - Additional keyword arguments for the CSV dialect. ### Methods - `__aiter__(self) -> self` - `async __anext__(self) -> Dict[str, str]` - `async get_fieldnames(self) -> List[str]` ### Properties - **fieldnames** (`List[str] | None`): Field names used when converting rows to dictionaries. Note: This property cannot read fieldnames if they are missing; use `await reader.get_fieldnames()` instead. - **restkey** (`str | None`): Key for storing extra cells in a row. - **restval** (`str | None`): Value for missing keys in a row. - **reader**: Underlying `aiofiles.AsyncReader` instance. ### Read-only properties - **dialect** (`aiocsv.protocols.DialectLike`): Link to `self.reader.dialect`. - **line_num** (`int`): The number of lines read from the source file. ``` -------------------------------- ### aiocsv.AsyncReader Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Asynchronous CSV reader. Accepts objects with an async `read(size: int)` coroutine. ```APIDOC ## aiocsv.AsyncReader ### Description An object that iterates over records in the given asynchronous CSV file. Additional keyword arguments are understood as dialect parameters. Iterating over this object returns parsed CSV rows (`List[str]`). ### Parameters #### Constructor Parameters - **asyncfile** (aiocsv.protocols.WithAsyncRead) - Required - An object with an async `read(size: int)` coroutine. - **dialect** (str | csv.Dialect | Type[csv.Dialect]) - Optional - Defaults to "excel". The CSV dialect to use. - **\*\*csv_dialect_kwargs** (aiocsv.protocols.CsvDialectKwargs) - Optional - Additional keyword arguments for CSV dialect parameters. ### Methods - `__aiter__(self) -> self` - `async __anext__(self) -> List[str]` ### Read-only properties - `dialect` (aiocsv.protocols.DialectLike): The dialect used when parsing. - `line_num` (int): The number of lines read from the source file. This coincides with a 1-based index of the line number of the last line of the recently parsed record. ### Request Example ```python import asyncio import aiofiles from aiocsv import AsyncReader async def read_csv(): async with aiofiles.open("some_file.csv", mode="r", encoding="utf-8", newline="") as afp: async for row in AsyncReader(afp): print(row) asyncio.run(read_csv()) ``` ``` -------------------------------- ### aiocsv.AsyncDictWriter Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md An object that writes CSV rows to an asynchronous file, using dictionaries for rows. ```APIDOC ## AsyncDictWriter ### Description An object that writes CSV rows to the given asynchronous file. In this object "row" is a mapping from fieldnames to values. Additional keyword arguments are passed to the underlying csv.DictWriter instance. ### Parameters - **asyncfile** (aiocsv.protocols.WithAsyncWrite) - Required - The asynchronous file object to write to. - **fieldnames** (Sequence[str]) - Required - Sequence of keys to identify the order of values when writing rows. - **restval** (Any) - Optional - Placeholder value used when a key from fieldnames is missing in a row, defaults to `""`. - **extrasaction** (Literal["raise", "ignore"]) - Optional - Action to take when there are keys in a row not present in fieldnames. Defaults to `"raise"`. - **dialect** (str | csv.Dialect | Type[csv.Dialect]) - Optional - The CSV dialect to use. Defaults to "excel". - **csv_dialect_kwargs** (Unpack[aiocsv.protocols.CsvDialectKwargs]) - Optional - Additional keyword arguments for the CSV dialect. ### Methods - `async writeheader(self) -> None`: Writes header row to the specified file. - `async writerow(self, row: Mapping[str, Any]) -> None`: Writes one row to the specified file. - `async writerows(self, rows: Iterable[Mapping[str, Any]]) -> None`: Writes multiple rows to the specified file. ### Properties - **fieldnames** (`Sequence[str]`): Sequence of keys to identify the order of values when writing rows. - **restval** (`Any`): Placeholder value used when a key from fieldnames is missing in a row. - **extrasaction** (`Literal["raise", "ignore"]`): Action to take on extra keys in a row. - **writer**: Link to the underlying `AsyncWriter`. ### Readonly properties - **dialect** (`aiocsv.protocols.DialectLike`): Link to underlying's csv.reader's `dialect` attribute. ``` -------------------------------- ### Ignore Extra Fields with AsyncDictWriter Source: https://context7.com/mkuranowski/aiocsv/llms.txt Use `extrasaction='ignore'` in AsyncDictWriter to silently skip dictionary keys that are not present in the `fieldnames`. The default behavior is to raise an error. ```python import asyncio import csv import aiofiles from aiocsv import AsyncDictWriter async def write_ignoring_extras(): async with aiofiles.open("output.csv", mode="w", encoding="utf-8", newline="") as afp: writer = AsyncDictWriter( afp, fieldnames=["name", "age"], extrasaction="ignore" # Silently ignore extra keys (default is "raise") ) await writer.writeheader() await writer.writerow({"name": "Alice", "age": 28, "extra_field": "ignored"}) asyncio.run(write_ignoring_extras()) ``` -------------------------------- ### aiocsv.AsyncWriter Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md Asynchronous CSV writer. Accepts objects with an async `write(b: str)` coroutine. ```APIDOC ## aiocsv.AsyncWriter ### Description An object that writes records to the given asynchronous CSV file. ### Parameters #### Constructor Parameters - **asyncfile** (aiocsv.protocols.WithAsyncWrite) - Required - An object with an async `write(b: str)` coroutine. - **dialect** (str | csv.Dialect | Type[csv.Dialect]) - Optional - Defaults to "excel". The CSV dialect to use. - **\*\*csv_dialect_kwargs** (aiocsv.protocols.CsvDialectKwargs) - Optional - Additional keyword arguments for CSV dialect parameters. ### Methods - `writerow(self, row: List[str]) -> Awaitable[int]` - `writerows(self, rows: Iterable[List[str]]) -> Awaitable[int]` ### Request Example ```python import asyncio import aiofiles from aiocsv import AsyncWriter async def write_csv(): async with aiofiles.open("new_file.csv", mode="w", encoding="utf-8", newline="") as afp: writer = AsyncWriter(afp, dialect="unix") await writer.writerow(["name", "age"]) await writer.writerows([ ["John", 26], ["Sasha", 42], ["Hana", 37] ]) asyncio.run(write_csv()) ``` ``` -------------------------------- ### aiocsv.AsyncWriter Source: https://github.com/mkuranowski/aiocsv/blob/master/readme.md An object that writes CSV rows to an asynchronous file. ```APIDOC ## AsyncWriter ### Description An object that writes CSV rows to the given asynchronous file. In this object "row" is a sequence of values. Additional keyword arguments are passed to the underlying csv.writer instance. ### Parameters - **asyncfile** (aiocsv.protocols.WithAsyncWrite) - Required - The asynchronous file object to write to. - **dialect** (str | csv.Dialect | Type[csv.Dialect]) - Optional - The CSV dialect to use. Defaults to "excel". - **csv_dialect_kwargs** (Unpack[aiocsv.protocols.CsvDialectKwargs]) - Optional - Additional keyword arguments for the CSV dialect. ### Methods - `async writerow(self, row: Iterable[Any]) -> None`: Writes one row to the specified file. - `async writerows(self, rows: Iterable[Iterable[Any]]) -> None`: Writes multiple rows to the specified file. ### Readonly properties - **dialect** (`aiocsv.protocols.DialectLike`): Link to underlying's csv.writer's `dialect` attribute. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.