rxn.utilities.csv.csv_iterator.CsvIterator

class rxn.utilities.csv.csv_iterator.CsvIterator(columns, rows)[source]

Bases: object

Class to easily iterate through CSV files while having easy access to the column names.

Note: the choice to not handle the file opening/closing in this class is on purpose. This avoids issue with keeping track of which files are open and when to close them.

Examples

>>> with open("some_file.csv", "rt") as f:
...     csv_iterator = CsvIterator.from_stream(f)
...     area_index = csv_iterator.column_index("area")
...     price_index = csv_iterator.column_index("price")
...     for row in csv_iterator.rows:
...         price = row[price_index]
...         area = row[area_index]
Parameters
  • columns (List[str]) –

  • rows (Iterator[List[str]]) –

__init__(columns, rows)[source]
Parameters
  • columns (List[str]) –

  • rows (Iterator[List[str]]) –

Methods

__init__(columns, rows)

param columns

column_index(column_name)

Get the index corresponding to the given column.

from_stream(stream[, delimiter])

Instantiate from a stream or file object.

to_stream(file[, delimiter, line_terminator])

param file

column_index(column_name)[source]

Get the index corresponding to the given column.

Parameters

column_name (str) – column to look up.

Raises

ValueError – if the column does not exist.

Return type

int

Returns

the index for the given column.

classmethod from_stream(stream, delimiter=',')[source]

Instantiate from a stream or file object.

Parameters
  • stream (TextIO) – stream or file object to instantiate from.

  • delimiter (str, default: ',') – CSV delimiter.

  • cls (Type[TypeVar(_CsvIteratorT, bound= CsvIterator)]) –

Return type

TypeVar(_CsvIteratorT, bound= CsvIterator)