dataflows-tabulator


Namedataflows-tabulator JSON
Version 1.54.3 PyPI version JSON
download
home_pagehttps://github.com/akariv/tabulator-py
SummaryConsistent interface for stream reading and writing tabular data (csv/xls/json/etc)
upload_time2024-03-24 13:58:15
maintainerNone
docs_urlNone
authorOpen Knowledge Foundation
requires_pythonNone
licenseMIT
keywords frictionless data
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage No coveralls.
            # dataflows-tabulator-py

[![PyPi](https://img.shields.io/pypi/v/dataflows-tabulator.svg)](https://pypi.python.org/pypi/dataflows-tabulator)
[![Github](https://img.shields.io/badge/github-master-brightgreen)](https://github.com/akariv/tabulator-py)

A library for reading and writing tabular data (csv/xls/json/etc).

> **[Important Notice]** This is a fork of the archived [tabulator-py](https://github.com/frictionlessdata/tabulator-py) repository. The original repository is no longer maintained. This fork is maintained by Adam Kariv.

## Features

- **Supports most common tabular formats**: CSV, XLS, ODS, JSON, Google Sheets, SQL, and others. See complete list [below](#supported-file-formats).
- **Loads local and remote data**: Supports HTTP, FTP and S3.
- **Low memory usage**: Only the current row is kept in memory, so you can
  large datasets.
- **Supports compressed files**: Using ZIP or GZIP algorithms.
- **Extensible**: You can add support for custom file formats and loaders (e.g.
  FTP).

## Contents

<!--TOC-->

  - [Getting started](#getting-started)
    - [Installation](#installation)
    - [Running on CLI](#running-on-cli)
    - [Running on Python](#running-on-python)
  - [Documentation](#documentation)
    - [Working with Stream](#working-with-stream)
    - [Supported schemes](#supported-schemes)
    - [Supported file formats](#supported-file-formats)
    - [Custom file sources and formats](#custom-file-sources-and-formats)
  - [API Reference](#api-reference)
    - [`cli`](#cli)
    - [`Stream`](#stream)
    - [`Loader`](#loader)
    - [`Parser`](#parser)
    - [`Writer`](#writer)
    - [`validate`](#validate)
    - [`TabulatorException`](#tabulatorexception)
    - [`SourceError`](#sourceerror)
    - [`SchemeError`](#schemeerror)
    - [`FormatError`](#formaterror)
    - [`EncodingError`](#encodingerror)
    - [`CompressionError`](#compressionerror)
    - [`IOError`](#ioerror)
    - [`LoadingError`](#loadingerror)
    - [`HTTPError`](#httperror)
  - [Contributing](#contributing)
  - [Changelog](#changelog)

<!--TOC-->

## Getting started

### Installation

```bash
$ pip install tabulator
```

### Running on CLI

Tabulator ships with a simple CLI called `tabulator` to read tabular data. For
example:

```bash
$ tabulator https://github.com/frictionlessdata/tabulator-py/raw/4c1b3943ac98be87b551d87a777d0f7ca4904701/data/table.csv.gz
id,name
1,english
2,中国人
```

You can see all supported options by running `tabulator --help`.

### Running on Python

```python
from tabulator import Stream

with Stream('data.csv', headers=1) as stream:
    stream.headers # [header1, header2, ..]
    for row in stream:
        print(row)  # [value1, value2, ..]
```

You can find other examples in the [examples][examples-dir] directory.

## Documentation

In the following sections, we'll walk through some usage examples of
this library. All examples were tested with Python 3.6, but should
run fine with Python 3.3+.

### Working with Stream

The `Stream` class represents a tabular stream. It takes the file path as the
`source` argument. For example:

```
<scheme>://path/to/file.<format>
```

It uses this path to determine the file format (e.g. CSV or XLS) and scheme
(e.g. HTTP or postgresql). It also supports format extraction from URLs like `http://example.com?format=csv`. If necessary, you also can define these explicitly.

Let's try it out. First, we create a `Stream` object passing the path to a CSV file.

```python
import tabulator

stream = tabulator.Stream('data.csv')
```

At this point, the file haven't been read yet. Let's open the stream so we can
read the contents.

```python
try:
    stream.open()
except tabulator.TabulatorException as e:
    pass  # Handle exception
```

This will open the underlying data stream, read a small sample to detect the
file encoding, and prepare the data to be read. We catch
`tabulator.TabulatorException` here, in case something goes wrong.

We can now read the file contents. To iterate over each row, we do:

```python
for row in stream.iter():
    print(row)  # [value1, value2, ...]
```

The `stream.iter()` method will return each row data as a list of values. If
you prefer, you could call `stream.iter(keyed=True)` instead, which returns a
dictionary with the column names as keys. Either way, this method keeps only a
single row in memory at a time. This means it can handle handle large files
without consuming too much memory.

If you want to read the entire file, use `stream.read()`. It accepts the same
arguments as `stream.iter()`, but returns all rows at once.

```python
stream.reset()
rows = stream.read()
```

Notice that we called `stream.reset()` before reading the rows. This is because
internally, tabulator only keeps a pointer to its current location in the file.
If we didn't reset this pointer, we would read starting from where we stopped.
For example, if we ran `stream.read()` again, we would get an empty list, as
the internal file pointer is at the end of the file (because we've already read
it all). Depending on the file location, it might be necessary to download the
file again to rewind (e.g. when the file was loaded from the web).

After we're done, close the stream with:

```python
stream.close()
```

The entire example looks like:

```python
import tabulator

stream = tabulator.Stream('data.csv')
try:
    stream.open()
except tabulator.TabulatorException as e:
    pass  # Handle exception

for row in stream.iter():
    print(row)  # [value1, value2, ...]

stream.reset()  # Rewind internal file pointer
rows = stream.read()

stream.close()
```

It could be rewritten to use Python's context manager interface as:

```python
import tabulator

try:
    with tabulator.Stream('data.csv') as stream:
        for row in stream.iter():
            print(row)

        stream.reset()
        rows = stream.read()
except tabulator.TabulatorException as e:
    pass
```

This is the preferred way, as Python closes the stream automatically, even if some exception was thrown along the way.

The full API documentation is available as docstrings in the [Stream source code][stream.py].

#### Headers

By default, tabulator considers that all file rows are values (i.e. there is no
header).

```python
with Stream([['name', 'age'], ['Alex', 21]]) as stream:
  stream.headers # None
  stream.read() # [['name', 'age'], ['Alex', 21]]
```

If you have a header row, you can use the `headers` argument with the its row
number (starting from 1).

```python
# Integer
with Stream([['name', 'age'], ['Alex', 21]], headers=1) as stream:
  stream.headers # ['name', 'age']
  stream.read() # [['Alex', 21]]
```

You can also pass a lists of strings to define the headers explicitly:

```python
with Stream([['Alex', 21]], headers=['name', 'age']) as stream:
  stream.headers # ['name', 'age']
  stream.read() # [['Alex', 21]]
```

Tabulator also supports multiline headers for the `xls` and `xlsx` formats.

```python
with Stream('data.xlsx', headers=[1, 3], fill_merged_cells=True) as stream:
  stream.headers # ['header from row 1-3']
  stream.read() # [['value1', 'value2', 'value3']]
```

#### Encoding

You can specify the file encoding (e.g. `utf-8` and `latin1`) via the `encoding`
argument.

```python
with Stream(source, encoding='latin1') as stream:
  stream.read()
```

If this argument isn't set, Tabulator will try to infer it from the data. If you
get a `UnicodeDecodeError` while loading a file, try setting the encoding to
`utf-8`.

#### Compression (Python3-only)

Tabulator supports both ZIP and GZIP compression methods. By default it'll infer from the file name:

```python
with Stream('http://example.com/data.csv.zip') as stream:
  stream.read()
```

You can also set it explicitly:

```python
with Stream('data.csv.ext', compression='gz') as stream:
  stream.read()
```
**Options**

- **filename**: filename in zip file to process (default is first file)

#### Allow html

The `Stream` class raises `tabulator.exceptions.FormatError` if it detects HTML
contents. This helps avoiding the relatively common mistake of trying to load a
CSV file inside an HTML page, for example on GitHub.

You can disable this behaviour using the `allow_html` option:

```python
with Stream(source_with_html, allow_html=True) as stream:
  stream.read() # no exception on open
```

#### Sample size

To detect the file's headers, and run other checks like validating that the file
doesn't contain HTML, Tabulator reads a sample of rows on the `stream.open()`
method. This data is available via the `stream.sample` property. The number of
rows used can be defined via the `sample_size` parameters (defaults to 100).

```python
with Stream(two_rows_source, sample_size=1) as stream:
  stream.sample # only first row
  stream.read() # first and second rows
```

You can disable this by setting `sample_size` to zero. This way, no data will be
read on `stream.open()`.

#### Bytes sample size

Tabulator needs to read a part of the file to infer its encoding. The
`bytes_sample_size` arguments controls how many bytes will be read for this
detection (defaults to 10000).

```python
source = 'data/special/latin1.csv'
with Stream(source) as stream:
    stream.encoding # 'iso8859-2'
```

You can disable this by setting `bytes_sample_size` to zero, in which case it'll
use the machine locale's default encoding.

#### Ignore blank headers

When `True`, tabulator will ignore columns that have blank headers (defaults to
`False`).

```python
# Default behaviour
source = 'text://header1,,header3\nvalue1,value2,value3'
with Stream(source, format='csv', headers=1) as stream:
    stream.headers # ['header1', '', 'header3']
    stream.read(keyed=True) # {'header1': 'value1', '': 'value2', 'header3': 'value3'}

# Ignoring columns with blank headers
source = 'text://header1,,header3\nvalue1,value2,value3'
with Stream(source, format='csv', headers=1, ignore_blank_headers=True) as stream:
    stream.headers # ['header1', 'header3']
    stream.read(keyed=True) # {'header1': 'value1', 'header3': 'value3'}
```

#### Ignore listed/not-listed headers

The option is similar to the `ignore_blank_headers`. It removes arbitrary columns from the data based on the corresponding column names:

```python
# Ignore listed headers (omit columns)
source = 'text://header1,header2,header3\nvalue1,value2,value3'
with Stream(source, format='csv', headers=1, ignore_listed_headers=['header2']) as stream:
    assert stream.headers == ['header1', 'header3']
    assert stream.read(keyed=True) == [
        {'header1': 'value1', 'header3': 'value3'},
    ]

# Ignore NOT listed headers (pick colums)
source = 'text://header1,header2,header3\nvalue1,value2,value3'
with Stream(source, format='csv', headers=1, ignore_not_listed_headers=['header2']) as stream:
    assert stream.headers == ['header2']
    assert stream.read(keyed=True) == [
        {'header2': 'value2'},
    ]
```

#### Force strings

When `True`, all rows' values will be converted to strings (defaults to
`False`). `None` values will be converted to empty strings.

```python
# Default behaviour
with Stream([['string', 1, datetime.datetime(2017, 12, 1, 17, 00)]]) as stream:
  stream.read() # [['string', 1, datetime.dateime(2017, 12, 1, 17, 00)]]

# Forcing rows' values as strings
with Stream([['string', 1]], force_strings=True) as stream:
  stream.read() # [['string', '1', '2017-12-01 17:00:00']]
```

#### Force parse

When `True`, don't raise an exception when parsing a malformed row, but simply
return an empty row. Otherwise, tabulator raises
`tabulator.exceptions.SourceError` when a row can't be parsed. Defaults to `False`.

```python
# Default behaviour
with Stream([[1], 'bad', [3]]) as stream:
  stream.read() # raises tabulator.exceptions.SourceError

# With force_parse
with Stream([[1], 'bad', [3]], force_parse=True) as stream:
  stream.read() # [[1], [], [3]]
```

#### Skip rows

List of row numbers and/or strings to skip.
If it's a string, all rows that begin with it will be skipped (e.g. '#' and '//').
If it's the empty string, all rows that begin with an empty column will be skipped.

```python
source = [['John', 1], ['Alex', 2], ['#Sam', 3], ['Mike', 4], ['John', 5]]
with Stream(source, skip_rows=[1, 2, -1, '#']) as stream:
  stream.read() # [['Mike', 4]]
```

If the `headers` parameter is also set to be an integer, it will use the first not skipped row as a headers.

```python
source = [['#comment'], ['name', 'order'], ['John', 1], ['Alex', 2]]
with Stream(source, headers=1, skip_rows=['#']) as stream:
  stream.headers # [['name', 'order']]
  stream.read() # [['Jogn', 1], ['Alex', 2]]
```

#### Post parse

List of functions that can filter or transform rows after they are parsed. These
functions receive the `extended_rows` containing the row's number, headers
list, and the row values list. They then process the rows, and yield or discard
them, modified or not.

```python
def skip_odd_rows(extended_rows):
    for row_number, headers, row in extended_rows:
        if not row_number % 2:
            yield (row_number, headers, row)

def multiply_by_two(extended_rows):
    for row_number, headers, row in extended_rows:
        doubled_row = list(map(lambda value: value * 2, row))
        yield (row_number, headers, doubled_row)

rows = [
  [1],
  [2],
  [3],
  [4],
]
with Stream(rows, post_parse=[skip_odd_rows, multiply_by_two]) as stream:
  stream.read() # [[4], [8]]
```

These functions are applied in order, as a simple data pipeline. In the example
above, `multiply_by_two` just sees the rows yielded by `skip_odd_rows`.

#### Keyed and extended rows

The methods `stream.iter()` and `stream.read()` accept the `keyed` and
`extended` flag arguments to modify how the rows are returned.

By default, every row is returned as a list of its cells values:

```python
with Stream([['name', 'age'], ['Alex', 21]]) as stream:
  stream.read() # [['Alex', 21]]
```

With `keyed=True`, the rows are returned as dictionaries, mapping the column names to their values in the row:

```python
with Stream([['name', 'age'], ['Alex', 21]]) as stream:
  stream.read(keyed=True) # [{'name': 'Alex', 'age': 21}]
```

And with `extended=True`, the rows are returned as a tuple of `(row_number,
headers, row)`, there `row_number` is the current row number (starting from 1),
`headers` is a list with the headers names, and `row` is a list with the rows
values:

```python
with Stream([['name', 'age'], ['Alex', 21]]) as stream:
  stream.read(extended=True) # (1, ['name', 'age'], ['Alex', 21])
```

### Supported schemes

#### s3

It loads data from AWS S3. For private files you should provide credentials supported by the `boto3` library, for example, corresponding environment variables. Read more about [configuring `boto3`](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html).

```python
stream = Stream('s3://bucket/data.csv')
```

**Options**

- **s3\_endpoint\_url** - the endpoint URL to use. By default it's `https://s3.amazonaws.com`. For complex use cases, for example, `goodtables`'s runs on a data package this option can be provided as an environment variable `S3_ENDPOINT_URL`.

#### file

The default scheme, a file in the local filesystem.

```python
stream = Stream('data.csv')
```

#### http/https/ftp/ftps

> In Python 2, `tabulator` can't stream remote data sources because of a limitation in the underlying libraries. The whole data source will be loaded to the memory. In Python 3 there is no such problem and remote files are streamed.

```python
stream = Stream('https://example.com/data.csv')
```

**Options**

- **http\_session** - a `requests.Session` object. Read more in the [requests docs][requests-session].
- **http\_stream** - Enables or disables HTTP streaming, when possible (enabled by default). Disable it if you'd like to preload the whole file into memory.
- **http\_timeout** - This timeout will be used for a `requests` session construction.

#### stream

The source is a file-like Python object.


```python
with open('data.csv') as fp:
    stream = Stream(fp)
```

#### text

The source is a string containing the tabular data. Both `scheme` and `format`
must be set explicitly, as it's not possible to infer them.

```python
stream = Stream(
    'name,age\nJohn, 21\n',
    scheme='text',
    format='csv'
)
```

### Supported file formats

In this section, we'll describe the supported file formats, and their respective
configuration options and operations. Some formats only support read operations,
while others support both reading and writing.

#### csv (read & write)

```python
stream = Stream('data.csv', delimiter=',')
```

**Options**

It supports all options from the Python CSV library. Check [their
documentation][pydoc-csv] for more information.

#### xls/xlsx (read & write)

> Tabulator is unable to stream `xls` files, so the entire file is loaded in
> memory. Streaming is supported for `xlsx` files.

```python
stream = Stream('data.xls', sheet=1)
```

**Options**

- **sheet**: Sheet name or number (starting from 1).
- **workbook_cache**: An empty dictionary to handle workbook caching. If provided, `tabulator` will fill the dictionary with `source: tmpfile_path` pairs for remote workbooks. Each workbook will be downloaded only once and all the temporary files will be deleted on the process exit. Defauts: None
- **fill_merged_cells**: if `True` it will unmerge and fill all merged cells by
  a visible value. With this option enabled the parser can't stream data and
  load the whole document into memory.
- **preserve_formatting**: if `True` it will try to preserve text formatting of numeric and temporal cells returning it as strings according to how it looks in a spreadsheet (EXPERIMETAL)
- **adjust_floating_point_error**: if `True` it will correct the Excel behaviour regarding floating point numbers

#### ods (read only)

> This format is not included to package by default. To use it please install `tabulator` with an `ods` extras: `$ pip install tabulator[ods]`

Source should be a valid Open Office document.

```python
stream = Stream('data.ods', sheet=1)
```

**Options**

- **sheet**: Sheet name or number (starting from 1)

#### gsheet (read only)

A publicly-accessible Google Spreadsheet.

```python
stream = Stream('https://docs.google.com/spreadsheets/d/<id>?usp=sharing')
stream = Stream('https://docs.google.com/spreadsheets/d/<id>edit#gid=<gid>')
```

#### sql (read & write)

Any database URL supported by [sqlalchemy][sqlalchemy].

```python
stream = Stream('postgresql://name:pass@host:5432/database', table='data')
```

**Options**

- **table (required)**: Database table name
- **order_by**: SQL expression for row ordering (e.g. `name DESC`)

#### Data Package (read only)

> This format is not included to package by default. You can enable it by
> installing tabulator using `pip install tabulator[datapackage]`.

A [Tabular Data Package][tdp].

```python
stream = Stream('datapackage.json', resource=1)
```

**Options**

- **resource**: Resource name or index (starting from 0)

#### inline (read only)

Either a list of lists, or a list of dicts mapping the column names to their
respective values.

```python
stream = Stream([['name', 'age'], ['John', 21], ['Alex', 33]])
stream = Stream([{'name': 'John', 'age': 21}, {'name': 'Alex', 'age': 33}])
```

#### json (read & write)

JSON document containing a list of lists, or a list of dicts mapping the column
names to their respective values (see the `inline` format for an example).

```python
stream = Stream('data.json', property='key1.key2')
```

**Options**

- **property**: JSON Path to the property containing the tabular data. For example, considering the JSON `{"response": {"data": [...]}}`, the `property` should be set to `response.data`.
- **keyed** (write): Save as array of arrays (default) or as array of dicts (keyed).

#### ndjson (read only)

```python
stream = Stream('data.ndjson')
```

#### tsv (read only)

```python
stream = Stream('data.tsv')
```

#### html (read only)


> This format is not included to package by default. To use it please install `tabulator` with the `html` extra: `$ pip install tabulator[html]`

An HTML table element residing inside an HTML document.

Supports simple tables (no merged cells) with any legal combination of the td, th, tbody & thead elements.

Usually `foramt='html'` would need to be specified explicitly as web URLs don't always use the `.html` extension.

```python
stream = Stream('http://example.com/some/page.aspx', format='html' selector='.content .data table#id1', raw_html=True)
```

**Options**

- **selector**: CSS selector for specifying which `table` element to extract. By default it's `table`, which takes the first `table` element in the document. If empty, will assume the entire page is the table to be extracted (useful with some Excel formats).

- **raw_html**: False (default) to extract the textual contents of each cell. True to return the inner html without modification.

### Custom file sources and formats

Tabulator is written with extensibility in mind, allowing you to add support for
new tabular file formats, schemes (e.g. ssh), and writers (e.g. MongoDB). There
are three components that allow this:

* Loaders
  * Loads a stream from some location (e.g. ssh)
* Parsers
  * Parses a stream of tabular data in some format (e.g. xls)
* Writers
  * Writes tabular data to some destination (e.g. MongoDB)

In this section, we'll see how to write custom classes to extend any of these components.

#### Custom loaders

You can add support for a new scheme (e.g. ssh) by creating a custom loader.
Custom loaders are implemented by inheriting from the `Loader` class, and
implementing its methods. This loader can then be used by `Stream` to load data
by passing it via the `custom_loaders={'scheme': CustomLoader}` argument.

The skeleton of a custom loader looks like:

```python
from tabulator import Loader

class CustomLoader(Loader):
  options = []

  def __init__(self, bytes_sample_size, **options):
      pass

  def load(self, source, mode='t', encoding=None):
      # load logic

with Stream(source, custom_loaders={'custom': CustomLoader}) as stream:
  stream.read()
```

You can see examples of how the loaders are implemented by looking in the
`tabulator.loaders` module.

#### Custom parsers

You can add support for a new file format by creating a custom parser. Similarly
to custom loaders, custom parsers are implemented by inheriting from the
`Parser` class, and implementing its methods. This parser can then be used by
`Stream` to parse data by passing it via the `custom_parsers={'format':
CustomParser}` argument.

The skeleton of a custom parser looks like:

```python
from tabulator import Parser

class CustomParser(Parser):
    options = []

    def __init__(self, loader, force_parse, **options):
        self.__loader = loader

    def open(self, source, encoding=None):
        # open logic

    def close(self):
        # close logic

    def reset(self):
        # reset logic

    @property
    def closed(self):
        return False

    @property
    def extended_rows(self):
        # extended rows logic

with Stream(source, custom_parsers={'custom': CustomParser}) as stream:
  stream.read()
```

You can see examples of how parsers are implemented by looking in the
`tabulator.parsers` module.

#### Custom writers

You can add support to write files in a specific format by creating a custom
writer. The custom writers are implemented by inheriting from the base `Writer`
class, and implementing its methods. This writer can then be used by `Stream` to
write data via the `custom_writers={'format': CustomWriter}` argument.

The skeleton of a custom writer looks like:

```python
from tabulator import Writer

class CustomWriter(Writer):
  options = []

  def __init__(self, **options):
      pass

  def write(self, source, target, headers=None, encoding=None):
      # write logic

with Stream(source, custom_writers={'custom': CustomWriter}) as stream:
  stream.save(target)
```

You can see examples of how parsers are implemented by looking in the
`tabulator.writers` module.

## API Reference

### `cli`
```python
cli(source, limit, **options)
```
Command-line interface

```
Usage: tabulator [OPTIONS] SOURCE

Options:
  --headers INTEGER
  --scheme TEXT
  --format TEXT
  --encoding TEXT
  --limit INTEGER
  --sheet TEXT/INTEGER (excel)
  --fill-merged-cells BOOLEAN (excel)
  --preserve-formatting BOOLEAN (excel)
  --adjust-floating-point-error BOOLEAN (excel)
  --table TEXT (sql)
  --order_by TEXT (sql)
  --resource TEXT/INTEGER (datapackage)
  --property TEXT (json)
  --keyed BOOLEAN (json)
  --version          Show the version and exit.
  --help             Show this message and exit.
```


### `Stream`
```python
Stream(self,
       source,
       headers=None,
       scheme=None,
       format=None,
       encoding=None,
       compression=None,
       allow_html=False,
       sample_size=100,
       bytes_sample_size=10000,
       ignore_blank_headers=False,
       ignore_listed_headers=None,
       ignore_not_listed_headers=None,
       multiline_headers_joiner=' ',
       multiline_headers_duplicates=False,
       force_strings=False,
       force_parse=False,
       pick_rows=None,
       skip_rows=None,
       pick_fields=None,
       skip_fields=None,
       pick_columns=None,
       skip_columns=None,
       post_parse=[],
       custom_loaders={},
       custom_parsers={},
       custom_writers={},
       **options)
```
Stream of tabular data.

This is the main `tabulator` class. It loads a data source, and allows you
to stream its parsed contents.

__Arguments__


    source (str):
        Path to file as ``<scheme>://path/to/file.<format>``.
        If not explicitly set, the scheme (file, http, ...) and
        format (csv, xls, ...) are inferred from the source string.

    headers (Union[int, List[int], List[str]], optional):
        Either a row
        number or list of row numbers (in case of multi-line headers) to be
        considered as headers (rows start counting at 1), or the actual
        headers defined a list of strings. If not set, all rows will be
        treated as containing values.

    scheme (str, optional):
        Scheme for loading the file (file, http, ...).
        If not set, it'll be inferred from `source`.

    format (str, optional):
        File source's format (csv, xls, ...). If not
        set, it'll be inferred from `source`. inferred

    encoding (str, optional):
        Source encoding. If not set, it'll be inferred.

    compression (str, optional):
        Source file compression (zip, ...). If not set, it'll be inferred.

    pick_rows (List[Union[int, str, dict]], optional):
        The same as `skip_rows` but it's for picking rows instead of skipping.

    skip_rows (List[Union[int, str, dict]], optional):
        List of row numbers, strings and regex patterns as dicts to skip.
        If a string, it'll skip rows that their first cells begin with it e.g. '#' and '//'.
        To skip only completely blank rows use `{'type': 'preset', 'value': 'blank'}`
        To try and auto detect the beginning of the table, use `{'type': 'preset', 'value': 'auto'}`
        To provide a regex pattern use  `{'type': 'regex', 'value': '^#'}`
        For example: `skip_rows=[1, '# comment', {'type': 'regex', 'value': '^# (regex|comment)'}]`

    pick_fields (str[]):
        When passed, ignores all columns with headers
        that the given list DOES NOT include

    skip_fields (str[]):
        When passed, ignores all columns with headers
        that the given list includes. If it contains an empty string it will skip
        empty headers

    sample_size (int, optional):
        Controls the number of sample rows used to
        infer properties from the data (headers, encoding, etc.). Set to
        ``0`` to disable sampling, in which case nothing will be inferred
        from the data. Defaults to ``config.DEFAULT_SAMPLE_SIZE``.

    bytes_sample_size (int, optional):
        Same as `sample_size`, but instead
        of number of rows, controls number of bytes. Defaults to
        ``config.DEFAULT_BYTES_SAMPLE_SIZE``.

    allow_html (bool, optional):
        Allow the file source to be an HTML page.
        If False, raises ``exceptions.FormatError`` if the loaded file is
        an HTML page. Defaults to False.

    multiline_headers_joiner (str, optional):
        When passed, it's used to join multiline headers
        as `<passed-value>.join(header1_1, header1_2)`
        Defaults to ' ' (space).

    multiline_headers_duplicates (bool, optional):
        By default tabulator will exclude a cell of a miltilne header from joining
        if it's exactly the same as the previous seen value in this field.
        Enabling this option will force duplicates inclusion
        Defaults to False.

    force_strings (bool, optional):
        When True, casts all data to strings.
        Defaults to False.

    force_parse (bool, optional):
        When True, don't raise exceptions when
        parsing malformed rows, simply returning an empty value. Defaults
        to False.

    post_parse (List[function], optional):
        List of generator functions that
        receives a list of rows and headers, processes them, and yields
        them (or not). Useful to pre-process the data. Defaults to None.

    custom_loaders (dict, optional):
        Dictionary with keys as scheme names,
        and values as their respective ``Loader`` class implementations.
        Defaults to None.

    custom_parsers (dict, optional):
        Dictionary with keys as format names,
        and values as their respective ``Parser`` class implementations.
        Defaults to None.

    custom_loaders (dict, optional):
        Dictionary with keys as writer format
        names, and values as their respective ``Writer`` class
        implementations. Defaults to None.

    **options (Any, optional): Extra options passed to the loaders and parsers.



#### `stream.closed`
Returns True if the underlying stream is closed, False otherwise.

__Returns__

`bool`: whether closed



#### `stream.compression`
Stream's compression ("no" if no compression)

__Returns__

`str`: compression



#### `stream.encoding`
Stream's encoding

__Returns__

`str`: encoding



#### `stream.format`
Path's format

__Returns__

`str`: format



#### `stream.fragment`
Path's fragment

__Returns__

`str`: fragment



#### `stream.hash`
Returns the SHA256 hash of the read chunks if available

__Returns__

`str/None`: SHA256 hash



#### `stream.headers`
Headers

__Returns__

`str[]/None`: headers if available



#### `stream.sample`
Returns the stream's rows used as sample.

These sample rows are used internally to infer characteristics of the
source file (e.g. encoding, headers, ...).

__Returns__

`list[]`: sample



#### `stream.scheme`
Path's scheme

__Returns__

`str`: scheme



#### `stream.size`
Returns the BYTE count of the read chunks if available

__Returns__

`int/None`: BYTE count



#### `stream.source`
Source

__Returns__

`any`: stream source



#### `stream.open`
```python
stream.open()
```
Opens the stream for reading.

__Raises:__

    TabulatorException: if an error



#### `stream.close`
```python
stream.close()
```
Closes the stream.


#### `stream.reset`
```python
stream.reset()
```
Resets the stream pointer to the beginning of the file.


#### `stream.iter`
```python
stream.iter(keyed=False, extended=False)
```
Iterate over the rows.

Each row is returned in a format that depends on the arguments `keyed`
and `extended`. By default, each row is returned as list of their
values.

__Arguments__
- __keyed (bool, optional)__:
        When True, each returned row will be a
        `dict` mapping the header name to its value in the current row.
        For example, `[{'name': 'J Smith', 'value': '10'}]`. Ignored if
        ``extended`` is True. Defaults to False.
- __extended (bool, optional)__:
        When True, returns each row as a tuple
        with row number (starts at 1), list of headers, and list of row
        values. For example, `(1, ['name', 'value'], ['J Smith', '10'])`.
        Defaults to False.

__Raises__
- `exceptions.TabulatorException`: If the stream is closed.

__Returns__

`Iterator[Union[List[Any], Dict[str, Any], Tuple[int, List[str], List[Any]]]]`:
        The row itself. The format depends on the values of `keyed` and
        `extended` arguments.



#### `stream.read`
```python
stream.read(keyed=False, extended=False, limit=None)
```
Returns a list of rows.

__Arguments__
- __keyed (bool, optional)__: See :func:`Stream.iter`.
- __extended (bool, optional)__: See :func:`Stream.iter`.
- __limit (int, optional)__:
        Number of rows to return. If None, returns all rows. Defaults to None.

__Returns__

`List[Union[List[Any], Dict[str, Any], Tuple[int, List[str], List[Any]]]]`:
        The list of rows. The format depends on the values of `keyed`
        and `extended` arguments.


#### `stream.save`
```python
stream.save(target, format=None, encoding=None, **options)
```
Save stream to the local filesystem.

__Arguments__
- __target (str)__: Path where to save the stream.
- __format (str, optional)__:
        The format the stream will be saved as. If
        None, detects from the ``target`` path. Defaults to None.
- __encoding (str, optional)__:
        Saved file encoding. Defaults to ``config.DEFAULT_ENCODING``.
- __**options__: Extra options passed to the writer.

__Returns__

`count (int?)`: Written rows count if available
Building index...
Started generating documentation...

### `Loader`
```python
Loader(self, bytes_sample_size, **options)
```
Abstract class implemented by the data loaders

The loaders inherit and implement this class' methods to add support for a
new scheme (e.g. ssh).

__Arguments__
- __bytes_sample_size (int)__: Sample size in bytes
- __**options (dict)__: Loader options



#### `loader.options`


#### `loader.load`
```python
loader.load(source, mode='t', encoding=None)
```
Load source file.

__Arguments__
- __source (str)__: Path to tabular source file.
- __mode (str, optional)__:
        Text stream mode, `t` (text) or `b` (binary).  Defaults to `t`.
- __encoding (str, optional)__:
        Source encoding. Auto-detect by default.

__Returns__

`Union[TextIO, BinaryIO]`: I/O stream opened either as text or binary.


### `Parser`
```python
Parser(self, loader, force_parse, **options)
```
Abstract class implemented by the data parsers.

The parsers inherit and implement this class' methods to add support for a
new file type.

__Arguments__
- __loader (tabulator.Loader)__: Loader instance to read the file.
- __force_parse (bool)__:
        When `True`, the parser yields an empty extended
        row tuple `(row_number, None, [])` when there is an error parsing a
        row. Otherwise, it stops the iteration by raising the exception
        `tabulator.exceptions.SourceError`.
- __**options (dict)__: Loader options



#### `parser.closed`
Flag telling if the parser is closed.

__Returns__

`bool`: whether closed



#### `parser.encoding`
Encoding

__Returns__

`str`: encoding



#### `parser.extended_rows`
Returns extended rows iterator.

The extended rows are tuples containing `(row_number, headers, row)`,

__Raises__
- `SourceError`:
        If `force_parse` is `False` and
        a row can't be parsed, this exception will be raised.
        Otherwise, an empty extended row is returned (i.e.
        `(row_number, None, [])`).

Returns:
    Iterator[Tuple[int, List[str], List[Any]]]:
        Extended rows containing
        `(row_number, headers, row)`, where `headers` is a list of the
        header names (can be `None`), and `row` is a list of row
        values.



#### `parser.options`


#### `parser.open`
```python
parser.open(source, encoding=None)
```
Open underlying file stream in the beginning of the file.

The parser gets a byte or text stream from the `tabulator.Loader`
instance and start emitting items.

__Arguments__
- __source (str)__: Path to source table.
- __encoding (str, optional)__: Source encoding. Auto-detect by default.

__Returns__

    None



#### `parser.close`
```python
parser.close()
```
Closes underlying file stream.


#### `parser.reset`
```python
parser.reset()
```
Resets underlying stream and current items list.

After `reset()` is called, iterating over the items will start from the beginning.

### `Writer`
```python
Writer(self, **options)
```
Abstract class implemented by the data writers.

The writers inherit and implement this class' methods to add support for a
new file destination.

__Arguments__
- __**options (dict)__: Writer options.



#### `writer.options`


#### `writer.write`
```python
writer.write(source, target, headers, encoding=None)
```
Writes source data to target.

__Arguments__
- __source (str)__: Source data.
- __target (str)__: Write target.
- __headers (List[str])__: List of header names.
- __encoding (str, optional)__: Source file encoding.

__Returns__

`count (int?)`: Written rows count if available


### `validate`
```python
validate(source, scheme=None, format=None)
```
Check if tabulator is able to load the source.

__Arguments__
- __source (Union[str, IO])__: The source path or IO object.
- __scheme (str, optional)__: The source scheme. Auto-detect by default.
- __format (str, optional)__: The source file format. Auto-detect by default.

__Raises__
- `SchemeError`: The file scheme is not supported.
- `FormatError`: The file format is not supported.

__Returns__

`bool`: Whether tabulator is able to load the source file.


### `TabulatorException`
```python
TabulatorException()
```
Base class for all tabulator exceptions.


### `SourceError`
```python
SourceError()
```
The source file could not be parsed correctly.


### `SchemeError`
```python
SchemeError()
```
The file scheme is not supported.


### `FormatError`
```python
FormatError()
```
The file format is unsupported or invalid.


### `EncodingError`
```python
EncodingError()
```
Encoding error


### `CompressionError`
```python
CompressionError()
```
Compression error


### `IOError`
```python
IOError()
```
Local loading error


### `LoadingError`
```python
LoadingError()
```
Local loading error


### `HTTPError`
```python
HTTPError()
```
Remote loading error

## Contributing

> The project follows the [Open Knowledge International coding standards](https://github.com/okfn/coding-standards).

Recommended way to get started is to create and activate a project virtual environment.
To install package and development dependencies into active environment:

```bash
$ make install
```

To run tests with linting and coverage:

```bash
$ make test
```

To run tests without Internet:

```
$ pytest -m 'not remote
```

## Changelog

Here described only breaking and the most important changes. The full changelog and documentation for all released versions could be found in nicely formatted [commit history](https://github.com/frictionlessdata/tabulator-py/commits/master).

#### v1.53

- Add support for raw_html extraction in html parser (#341)

#### v1.52

- Published stream.dialect (works only for csv, for now)

#### v1.51

- Added experimental table discovery options

#### v1.50

- Ensure that headers is always a list of strings

#### v1.49

- Added `workbook_cache` argument for XLSX formats

#### v1.48

- Published `stream.hashing_algorithm` property

#### v1.47

- Added `hashing_algorithm` parameter

#### v1.46

- Fixed multiline headers merging
- Introduced a `multiline_headers_duplicates` flag

#### v1.45

- HTML format: adds support for empty selector (#321)

#### v1.44

- Exposed `stream.compression`

#### v1.43

- Exposed `stream.source`

#### v1.42

- Exposed format option to the CLI

#### v1.41

- Implemented a `pick_rows` parameter (opposite to `skip_rows`)

#### v1.40

- Implemented `stream.save()` returning count of written rows

#### v1.39

- Implemented JSON writer (#311)

#### v1.38

- Use `chardet` for encoding detection by default. For `cchardet`: `pip install tabulator[cchardet]`. Due to a great deal of problems caused by `ccharted` for non-Linux/Conda installations we're returning back to using `chardet` by default.

#### v1.37

- Raise IOError/HTTPError even a not-existent file has a bad format (#304)

#### v1.36

- Implemented `blank` preset for `skip_rows` (#302)

#### v1.35

- Added `skip/pick_columns` aliases for (#293)

#### v1.34

- Added `multiline_headers_joiner` argument (#291)

#### v1.33

- Added support for regex patterns in `skip_rows` (#290)

#### v1.32

- Added ability to skip columns (#293)

#### v1.31

- Added `xlsx` writer
- Added `html` reader

#### v1.30

- Added `adjust_floating_point_error` parameter to the `xlsx` parser

#### v1.29

- Implemented the `stream.size` and `stream.hash` properties

#### v1.28

- Added SQL writer

#### v1.27

- Added `http_timeout` argument for the `http/https` format

#### v1.26

- Added `stream.fragment` field showing e.g. Excel sheet's or DP resource's name

#### v1.25

- Added support for the `s3` file scheme (data loading from AWS S3)

#### v1.24

- Added support for compressed file-like objects

#### v1.23

- Added a setter for the `stream.headers` property

#### v1.22

- The `headers` parameter will now use the first not skipped row if the `skip_rows` parameter is provided and there are comments on the top of a data source (see #264)

#### v1.21

- Implemented experimental `preserve_formatting` for xlsx

#### v1.20

- Added support for specifying filename in zip source

#### v1.19

Updated behaviour:
- For `ods` format the boolean, integer and datetime native types are detected now

#### v1.18

Updated behaviour:
- For `xls` format the boolean, integer and datetime native types are detected now

#### v1.17

Updated behaviour:
- Added support for Python 3.7

#### v1.16

New API added:
- `skip_rows` support for an empty string to skip rows with an empty first column

#### v1.15

New API added:
- Format will be extracted from URLs like `http://example.com?format=csv`

#### v1.14

Updated behaviour:
- Now `xls` booleans will be parsed as booleans not integers

#### v1.13

New API added:
- The `skip_rows` argument now supports negative numbers to skip rows starting from the end

#### v1.12

Updated behaviour:
- Instead of raising an exception, a `UserWarning` warning will be emitted if an option isn't recognized.

#### v1.11

New API added:
- Added `http_session` argument for the `http/https` format (it uses `requests` now)
- Added support for multiline headers: `headers` argument accept ranges like `[1,3]`

#### v1.10

New API added:
- Added support for compressed files i.e. `zip` and `gz` on Python3
- The `Stream` constructor now accepts a `compression` argument
- The `http/https` scheme now accepts a `http_stream` flag

#### v1.9

Improved behaviour:
- The `headers` argument allows to set the order for keyed sources and cherry-pick values

#### v1.8

New API added:
- Formats `XLS/XLSX/ODS` supports sheet names passed via the `sheet` argument
- The `Stream` constructor accepts an `ignore_blank_headers` option

#### v1.7

Improved behaviour:
- Rebased `datapackage` format on `datapackage@1` library

#### v1.6

New API added:
- Argument `source` for the `Stream` constructor can be a `pathlib.Path`

#### v1.5

New API added:
- Argument `bytes_sample_size` for the `Stream` constructor

#### v1.4

Improved behaviour:
- Updated encoding name to a canonical form

#### v1.3

New API added:
- `stream.scheme`
- `stream.format`
- `stream.encoding`

Promoted provisional API to stable API:
- `Loader` (custom loaders)
- `Parser` (custom parsers)
- `Writer` (custom writers)
- `validate`

#### v1.2

Improved behaviour:
- Autodetect common CSV delimiters

#### v1.1

New API added:
- Added `fill_merged_cells` option to `xls/xlsx` formats

#### v1.0

New API added:
- published `Loader/Parser/Writer` API
- Added `Stream` argument `force_strings`
- Added `Stream` argument `force_parse`
- Added `Stream` argument `custom_writers`

Deprecated API removal:
- removed `topen` and `Table` - use `Stream` instead
- removed `Stream` arguments `loader/parser_options` - use `**options` instead

Provisional API changed:
- Updated the `Loader/Parser/Writer` API - please use an updated version

#### v0.15

Provisional API added:
- Unofficial support for `Stream` arguments `custom_loaders/parsers`


[stream.py]: tabulator/stream.py
[examples-dir]: examples "Examples"
[requests-session]: https://docs.puthon-requests.org/en/master/user/advanced/#session-objects
[pydoc-csv]: https://docs.python.org/3/library/csv.html#dialects-and-formatting-parameters "Python CSV options"
[sqlalchemy]: https://www.sqlalchemy.org/
[tdp]: https://frictionlessdata.io/specs/tabular-data-package/ "Tabular Data Package"
[tabulator.exceptions]: tabulator/exceptions.py "Tabulator Exceptions"

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/akariv/tabulator-py",
    "name": "dataflows-tabulator",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "frictionless data",
    "author": "Open Knowledge Foundation",
    "author_email": "info@okfn.org",
    "download_url": "https://files.pythonhosted.org/packages/32/d7/0a540880fb7fe287227fa55a98e0f1aeff13a9785c6c77cbae66e2ce922f/dataflows-tabulator-1.54.3.tar.gz",
    "platform": null,
    "description": "# dataflows-tabulator-py\n\n[![PyPi](https://img.shields.io/pypi/v/dataflows-tabulator.svg)](https://pypi.python.org/pypi/dataflows-tabulator)\n[![Github](https://img.shields.io/badge/github-master-brightgreen)](https://github.com/akariv/tabulator-py)\n\nA library for reading and writing tabular data (csv/xls/json/etc).\n\n> **[Important Notice]** This is a fork of the archived [tabulator-py](https://github.com/frictionlessdata/tabulator-py) repository. The original repository is no longer maintained. This fork is maintained by Adam Kariv.\n\n## Features\n\n- **Supports most common tabular formats**: CSV, XLS, ODS, JSON, Google Sheets, SQL, and others. See complete list [below](#supported-file-formats).\n- **Loads local and remote data**: Supports HTTP, FTP and S3.\n- **Low memory usage**: Only the current row is kept in memory, so you can\n  large datasets.\n- **Supports compressed files**: Using ZIP or GZIP algorithms.\n- **Extensible**: You can add support for custom file formats and loaders (e.g.\n  FTP).\n\n## Contents\n\n<!--TOC-->\n\n  - [Getting started](#getting-started)\n    - [Installation](#installation)\n    - [Running on CLI](#running-on-cli)\n    - [Running on Python](#running-on-python)\n  - [Documentation](#documentation)\n    - [Working with Stream](#working-with-stream)\n    - [Supported schemes](#supported-schemes)\n    - [Supported file formats](#supported-file-formats)\n    - [Custom file sources and formats](#custom-file-sources-and-formats)\n  - [API Reference](#api-reference)\n    - [`cli`](#cli)\n    - [`Stream`](#stream)\n    - [`Loader`](#loader)\n    - [`Parser`](#parser)\n    - [`Writer`](#writer)\n    - [`validate`](#validate)\n    - [`TabulatorException`](#tabulatorexception)\n    - [`SourceError`](#sourceerror)\n    - [`SchemeError`](#schemeerror)\n    - [`FormatError`](#formaterror)\n    - [`EncodingError`](#encodingerror)\n    - [`CompressionError`](#compressionerror)\n    - [`IOError`](#ioerror)\n    - [`LoadingError`](#loadingerror)\n    - [`HTTPError`](#httperror)\n  - [Contributing](#contributing)\n  - [Changelog](#changelog)\n\n<!--TOC-->\n\n## Getting started\n\n### Installation\n\n```bash\n$ pip install tabulator\n```\n\n### Running on CLI\n\nTabulator ships with a simple CLI called `tabulator` to read tabular data. For\nexample:\n\n```bash\n$ tabulator https://github.com/frictionlessdata/tabulator-py/raw/4c1b3943ac98be87b551d87a777d0f7ca4904701/data/table.csv.gz\nid,name\n1,english\n2,\u4e2d\u56fd\u4eba\n```\n\nYou can see all supported options by running `tabulator --help`.\n\n### Running on Python\n\n```python\nfrom tabulator import Stream\n\nwith Stream('data.csv', headers=1) as stream:\n    stream.headers # [header1, header2, ..]\n    for row in stream:\n        print(row)  # [value1, value2, ..]\n```\n\nYou can find other examples in the [examples][examples-dir] directory.\n\n## Documentation\n\nIn the following sections, we'll walk through some usage examples of\nthis library. All examples were tested with Python 3.6, but should\nrun fine with Python 3.3+.\n\n### Working with Stream\n\nThe `Stream` class represents a tabular stream. It takes the file path as the\n`source` argument. For example:\n\n```\n<scheme>://path/to/file.<format>\n```\n\nIt uses this path to determine the file format (e.g. CSV or XLS) and scheme\n(e.g. HTTP or postgresql). It also supports format extraction from URLs like `http://example.com?format=csv`. If necessary, you also can define these explicitly.\n\nLet's try it out. First, we create a `Stream` object passing the path to a CSV file.\n\n```python\nimport tabulator\n\nstream = tabulator.Stream('data.csv')\n```\n\nAt this point, the file haven't been read yet. Let's open the stream so we can\nread the contents.\n\n```python\ntry:\n    stream.open()\nexcept tabulator.TabulatorException as e:\n    pass  # Handle exception\n```\n\nThis will open the underlying data stream, read a small sample to detect the\nfile encoding, and prepare the data to be read. We catch\n`tabulator.TabulatorException` here, in case something goes wrong.\n\nWe can now read the file contents. To iterate over each row, we do:\n\n```python\nfor row in stream.iter():\n    print(row)  # [value1, value2, ...]\n```\n\nThe `stream.iter()` method will return each row data as a list of values. If\nyou prefer, you could call `stream.iter(keyed=True)` instead, which returns a\ndictionary with the column names as keys. Either way, this method keeps only a\nsingle row in memory at a time. This means it can handle handle large files\nwithout consuming too much memory.\n\nIf you want to read the entire file, use `stream.read()`. It accepts the same\narguments as `stream.iter()`, but returns all rows at once.\n\n```python\nstream.reset()\nrows = stream.read()\n```\n\nNotice that we called `stream.reset()` before reading the rows. This is because\ninternally, tabulator only keeps a pointer to its current location in the file.\nIf we didn't reset this pointer, we would read starting from where we stopped.\nFor example, if we ran `stream.read()` again, we would get an empty list, as\nthe internal file pointer is at the end of the file (because we've already read\nit all). Depending on the file location, it might be necessary to download the\nfile again to rewind (e.g. when the file was loaded from the web).\n\nAfter we're done, close the stream with:\n\n```python\nstream.close()\n```\n\nThe entire example looks like:\n\n```python\nimport tabulator\n\nstream = tabulator.Stream('data.csv')\ntry:\n    stream.open()\nexcept tabulator.TabulatorException as e:\n    pass  # Handle exception\n\nfor row in stream.iter():\n    print(row)  # [value1, value2, ...]\n\nstream.reset()  # Rewind internal file pointer\nrows = stream.read()\n\nstream.close()\n```\n\nIt could be rewritten to use Python's context manager interface as:\n\n```python\nimport tabulator\n\ntry:\n    with tabulator.Stream('data.csv') as stream:\n        for row in stream.iter():\n            print(row)\n\n        stream.reset()\n        rows = stream.read()\nexcept tabulator.TabulatorException as e:\n    pass\n```\n\nThis is the preferred way, as Python closes the stream automatically, even if some exception was thrown along the way.\n\nThe full API documentation is available as docstrings in the [Stream source code][stream.py].\n\n#### Headers\n\nBy default, tabulator considers that all file rows are values (i.e. there is no\nheader).\n\n```python\nwith Stream([['name', 'age'], ['Alex', 21]]) as stream:\n  stream.headers # None\n  stream.read() # [['name', 'age'], ['Alex', 21]]\n```\n\nIf you have a header row, you can use the `headers` argument with the its row\nnumber (starting from 1).\n\n```python\n# Integer\nwith Stream([['name', 'age'], ['Alex', 21]], headers=1) as stream:\n  stream.headers # ['name', 'age']\n  stream.read() # [['Alex', 21]]\n```\n\nYou can also pass a lists of strings to define the headers explicitly:\n\n```python\nwith Stream([['Alex', 21]], headers=['name', 'age']) as stream:\n  stream.headers # ['name', 'age']\n  stream.read() # [['Alex', 21]]\n```\n\nTabulator also supports multiline headers for the `xls` and `xlsx` formats.\n\n```python\nwith Stream('data.xlsx', headers=[1, 3], fill_merged_cells=True) as stream:\n  stream.headers # ['header from row 1-3']\n  stream.read() # [['value1', 'value2', 'value3']]\n```\n\n#### Encoding\n\nYou can specify the file encoding (e.g. `utf-8` and `latin1`) via the `encoding`\nargument.\n\n```python\nwith Stream(source, encoding='latin1') as stream:\n  stream.read()\n```\n\nIf this argument isn't set, Tabulator will try to infer it from the data. If you\nget a `UnicodeDecodeError` while loading a file, try setting the encoding to\n`utf-8`.\n\n#### Compression (Python3-only)\n\nTabulator supports both ZIP and GZIP compression methods. By default it'll infer from the file name:\n\n```python\nwith Stream('http://example.com/data.csv.zip') as stream:\n  stream.read()\n```\n\nYou can also set it explicitly:\n\n```python\nwith Stream('data.csv.ext', compression='gz') as stream:\n  stream.read()\n```\n**Options**\n\n- **filename**: filename in zip file to process (default is first file)\n\n#### Allow html\n\nThe `Stream` class raises `tabulator.exceptions.FormatError` if it detects HTML\ncontents. This helps avoiding the relatively common mistake of trying to load a\nCSV file inside an HTML page, for example on GitHub.\n\nYou can disable this behaviour using the `allow_html` option:\n\n```python\nwith Stream(source_with_html, allow_html=True) as stream:\n  stream.read() # no exception on open\n```\n\n#### Sample size\n\nTo detect the file's headers, and run other checks like validating that the file\ndoesn't contain HTML, Tabulator reads a sample of rows on the `stream.open()`\nmethod. This data is available via the `stream.sample` property. The number of\nrows used can be defined via the `sample_size` parameters (defaults to 100).\n\n```python\nwith Stream(two_rows_source, sample_size=1) as stream:\n  stream.sample # only first row\n  stream.read() # first and second rows\n```\n\nYou can disable this by setting `sample_size` to zero. This way, no data will be\nread on `stream.open()`.\n\n#### Bytes sample size\n\nTabulator needs to read a part of the file to infer its encoding. The\n`bytes_sample_size` arguments controls how many bytes will be read for this\ndetection (defaults to 10000).\n\n```python\nsource = 'data/special/latin1.csv'\nwith Stream(source) as stream:\n    stream.encoding # 'iso8859-2'\n```\n\nYou can disable this by setting `bytes_sample_size` to zero, in which case it'll\nuse the machine locale's default encoding.\n\n#### Ignore blank headers\n\nWhen `True`, tabulator will ignore columns that have blank headers (defaults to\n`False`).\n\n```python\n# Default behaviour\nsource = 'text://header1,,header3\\nvalue1,value2,value3'\nwith Stream(source, format='csv', headers=1) as stream:\n    stream.headers # ['header1', '', 'header3']\n    stream.read(keyed=True) # {'header1': 'value1', '': 'value2', 'header3': 'value3'}\n\n# Ignoring columns with blank headers\nsource = 'text://header1,,header3\\nvalue1,value2,value3'\nwith Stream(source, format='csv', headers=1, ignore_blank_headers=True) as stream:\n    stream.headers # ['header1', 'header3']\n    stream.read(keyed=True) # {'header1': 'value1', 'header3': 'value3'}\n```\n\n#### Ignore listed/not-listed headers\n\nThe option is similar to the `ignore_blank_headers`. It removes arbitrary columns from the data based on the corresponding column names:\n\n```python\n# Ignore listed headers (omit columns)\nsource = 'text://header1,header2,header3\\nvalue1,value2,value3'\nwith Stream(source, format='csv', headers=1, ignore_listed_headers=['header2']) as stream:\n    assert stream.headers == ['header1', 'header3']\n    assert stream.read(keyed=True) == [\n        {'header1': 'value1', 'header3': 'value3'},\n    ]\n\n# Ignore NOT listed headers (pick colums)\nsource = 'text://header1,header2,header3\\nvalue1,value2,value3'\nwith Stream(source, format='csv', headers=1, ignore_not_listed_headers=['header2']) as stream:\n    assert stream.headers == ['header2']\n    assert stream.read(keyed=True) == [\n        {'header2': 'value2'},\n    ]\n```\n\n#### Force strings\n\nWhen `True`, all rows' values will be converted to strings (defaults to\n`False`). `None` values will be converted to empty strings.\n\n```python\n# Default behaviour\nwith Stream([['string', 1, datetime.datetime(2017, 12, 1, 17, 00)]]) as stream:\n  stream.read() # [['string', 1, datetime.dateime(2017, 12, 1, 17, 00)]]\n\n# Forcing rows' values as strings\nwith Stream([['string', 1]], force_strings=True) as stream:\n  stream.read() # [['string', '1', '2017-12-01 17:00:00']]\n```\n\n#### Force parse\n\nWhen `True`, don't raise an exception when parsing a malformed row, but simply\nreturn an empty row. Otherwise, tabulator raises\n`tabulator.exceptions.SourceError` when a row can't be parsed. Defaults to `False`.\n\n```python\n# Default behaviour\nwith Stream([[1], 'bad', [3]]) as stream:\n  stream.read() # raises tabulator.exceptions.SourceError\n\n# With force_parse\nwith Stream([[1], 'bad', [3]], force_parse=True) as stream:\n  stream.read() # [[1], [], [3]]\n```\n\n#### Skip rows\n\nList of row numbers and/or strings to skip.\nIf it's a string, all rows that begin with it will be skipped (e.g. '#' and '//').\nIf it's the empty string, all rows that begin with an empty column will be skipped.\n\n```python\nsource = [['John', 1], ['Alex', 2], ['#Sam', 3], ['Mike', 4], ['John', 5]]\nwith Stream(source, skip_rows=[1, 2, -1, '#']) as stream:\n  stream.read() # [['Mike', 4]]\n```\n\nIf the `headers` parameter is also set to be an integer, it will use the first not skipped row as a headers.\n\n```python\nsource = [['#comment'], ['name', 'order'], ['John', 1], ['Alex', 2]]\nwith Stream(source, headers=1, skip_rows=['#']) as stream:\n  stream.headers # [['name', 'order']]\n  stream.read() # [['Jogn', 1], ['Alex', 2]]\n```\n\n#### Post parse\n\nList of functions that can filter or transform rows after they are parsed. These\nfunctions receive the `extended_rows` containing the row's number, headers\nlist, and the row values list. They then process the rows, and yield or discard\nthem, modified or not.\n\n```python\ndef skip_odd_rows(extended_rows):\n    for row_number, headers, row in extended_rows:\n        if not row_number % 2:\n            yield (row_number, headers, row)\n\ndef multiply_by_two(extended_rows):\n    for row_number, headers, row in extended_rows:\n        doubled_row = list(map(lambda value: value * 2, row))\n        yield (row_number, headers, doubled_row)\n\nrows = [\n  [1],\n  [2],\n  [3],\n  [4],\n]\nwith Stream(rows, post_parse=[skip_odd_rows, multiply_by_two]) as stream:\n  stream.read() # [[4], [8]]\n```\n\nThese functions are applied in order, as a simple data pipeline. In the example\nabove, `multiply_by_two` just sees the rows yielded by `skip_odd_rows`.\n\n#### Keyed and extended rows\n\nThe methods `stream.iter()` and `stream.read()` accept the `keyed` and\n`extended` flag arguments to modify how the rows are returned.\n\nBy default, every row is returned as a list of its cells values:\n\n```python\nwith Stream([['name', 'age'], ['Alex', 21]]) as stream:\n  stream.read() # [['Alex', 21]]\n```\n\nWith `keyed=True`, the rows are returned as dictionaries, mapping the column names to their values in the row:\n\n```python\nwith Stream([['name', 'age'], ['Alex', 21]]) as stream:\n  stream.read(keyed=True) # [{'name': 'Alex', 'age': 21}]\n```\n\nAnd with `extended=True`, the rows are returned as a tuple of `(row_number,\nheaders, row)`, there `row_number` is the current row number (starting from 1),\n`headers` is a list with the headers names, and `row` is a list with the rows\nvalues:\n\n```python\nwith Stream([['name', 'age'], ['Alex', 21]]) as stream:\n  stream.read(extended=True) # (1, ['name', 'age'], ['Alex', 21])\n```\n\n### Supported schemes\n\n#### s3\n\nIt loads data from AWS S3. For private files you should provide credentials supported by the `boto3` library, for example, corresponding environment variables. Read more about [configuring `boto3`](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html).\n\n```python\nstream = Stream('s3://bucket/data.csv')\n```\n\n**Options**\n\n- **s3\\_endpoint\\_url** - the endpoint URL to use. By default it's `https://s3.amazonaws.com`. For complex use cases, for example, `goodtables`'s runs on a data package this option can be provided as an environment variable `S3_ENDPOINT_URL`.\n\n#### file\n\nThe default scheme, a file in the local filesystem.\n\n```python\nstream = Stream('data.csv')\n```\n\n#### http/https/ftp/ftps\n\n> In Python 2, `tabulator` can't stream remote data sources because of a limitation in the underlying libraries. The whole data source will be loaded to the memory. In Python 3 there is no such problem and remote files are streamed.\n\n```python\nstream = Stream('https://example.com/data.csv')\n```\n\n**Options**\n\n- **http\\_session** - a `requests.Session` object. Read more in the [requests docs][requests-session].\n- **http\\_stream** - Enables or disables HTTP streaming, when possible (enabled by default). Disable it if you'd like to preload the whole file into memory.\n- **http\\_timeout** - This timeout will be used for a `requests` session construction.\n\n#### stream\n\nThe source is a file-like Python object.\n\n\n```python\nwith open('data.csv') as fp:\n    stream = Stream(fp)\n```\n\n#### text\n\nThe source is a string containing the tabular data. Both `scheme` and `format`\nmust be set explicitly, as it's not possible to infer them.\n\n```python\nstream = Stream(\n    'name,age\\nJohn, 21\\n',\n    scheme='text',\n    format='csv'\n)\n```\n\n### Supported file formats\n\nIn this section, we'll describe the supported file formats, and their respective\nconfiguration options and operations. Some formats only support read operations,\nwhile others support both reading and writing.\n\n#### csv (read & write)\n\n```python\nstream = Stream('data.csv', delimiter=',')\n```\n\n**Options**\n\nIt supports all options from the Python CSV library. Check [their\ndocumentation][pydoc-csv] for more information.\n\n#### xls/xlsx (read & write)\n\n> Tabulator is unable to stream `xls` files, so the entire file is loaded in\n> memory. Streaming is supported for `xlsx` files.\n\n```python\nstream = Stream('data.xls', sheet=1)\n```\n\n**Options**\n\n- **sheet**: Sheet name or number (starting from 1).\n- **workbook_cache**: An empty dictionary to handle workbook caching. If provided, `tabulator` will fill the dictionary with `source: tmpfile_path` pairs for remote workbooks. Each workbook will be downloaded only once and all the temporary files will be deleted on the process exit. Defauts: None\n- **fill_merged_cells**: if `True` it will unmerge and fill all merged cells by\n  a visible value. With this option enabled the parser can't stream data and\n  load the whole document into memory.\n- **preserve_formatting**: if `True` it will try to preserve text formatting of numeric and temporal cells returning it as strings according to how it looks in a spreadsheet (EXPERIMETAL)\n- **adjust_floating_point_error**: if `True` it will correct the Excel behaviour regarding floating point numbers\n\n#### ods (read only)\n\n> This format is not included to package by default. To use it please install `tabulator` with an `ods` extras: `$ pip install tabulator[ods]`\n\nSource should be a valid Open Office document.\n\n```python\nstream = Stream('data.ods', sheet=1)\n```\n\n**Options**\n\n- **sheet**: Sheet name or number (starting from 1)\n\n#### gsheet (read only)\n\nA publicly-accessible Google Spreadsheet.\n\n```python\nstream = Stream('https://docs.google.com/spreadsheets/d/<id>?usp=sharing')\nstream = Stream('https://docs.google.com/spreadsheets/d/<id>edit#gid=<gid>')\n```\n\n#### sql (read & write)\n\nAny database URL supported by [sqlalchemy][sqlalchemy].\n\n```python\nstream = Stream('postgresql://name:pass@host:5432/database', table='data')\n```\n\n**Options**\n\n- **table (required)**: Database table name\n- **order_by**: SQL expression for row ordering (e.g. `name DESC`)\n\n#### Data Package (read only)\n\n> This format is not included to package by default. You can enable it by\n> installing tabulator using `pip install tabulator[datapackage]`.\n\nA [Tabular Data Package][tdp].\n\n```python\nstream = Stream('datapackage.json', resource=1)\n```\n\n**Options**\n\n- **resource**: Resource name or index (starting from 0)\n\n#### inline (read only)\n\nEither a list of lists, or a list of dicts mapping the column names to their\nrespective values.\n\n```python\nstream = Stream([['name', 'age'], ['John', 21], ['Alex', 33]])\nstream = Stream([{'name': 'John', 'age': 21}, {'name': 'Alex', 'age': 33}])\n```\n\n#### json (read & write)\n\nJSON document containing a list of lists, or a list of dicts mapping the column\nnames to their respective values (see the `inline` format for an example).\n\n```python\nstream = Stream('data.json', property='key1.key2')\n```\n\n**Options**\n\n- **property**: JSON Path to the property containing the tabular data. For example, considering the JSON `{\"response\": {\"data\": [...]}}`, the `property` should be set to `response.data`.\n- **keyed** (write): Save as array of arrays (default) or as array of dicts (keyed).\n\n#### ndjson (read only)\n\n```python\nstream = Stream('data.ndjson')\n```\n\n#### tsv (read only)\n\n```python\nstream = Stream('data.tsv')\n```\n\n#### html (read only)\n\n\n> This format is not included to package by default. To use it please install `tabulator` with the `html` extra: `$ pip install tabulator[html]`\n\nAn HTML table element residing inside an HTML document.\n\nSupports simple tables (no merged cells) with any legal combination of the td, th, tbody & thead elements.\n\nUsually `foramt='html'` would need to be specified explicitly as web URLs don't always use the `.html` extension.\n\n```python\nstream = Stream('http://example.com/some/page.aspx', format='html' selector='.content .data table#id1', raw_html=True)\n```\n\n**Options**\n\n- **selector**: CSS selector for specifying which `table` element to extract. By default it's `table`, which takes the first `table` element in the document. If empty, will assume the entire page is the table to be extracted (useful with some Excel formats).\n\n- **raw_html**: False (default) to extract the textual contents of each cell. True to return the inner html without modification.\n\n### Custom file sources and formats\n\nTabulator is written with extensibility in mind, allowing you to add support for\nnew tabular file formats, schemes (e.g. ssh), and writers (e.g. MongoDB). There\nare three components that allow this:\n\n* Loaders\n  * Loads a stream from some location (e.g. ssh)\n* Parsers\n  * Parses a stream of tabular data in some format (e.g. xls)\n* Writers\n  * Writes tabular data to some destination (e.g. MongoDB)\n\nIn this section, we'll see how to write custom classes to extend any of these components.\n\n#### Custom loaders\n\nYou can add support for a new scheme (e.g. ssh) by creating a custom loader.\nCustom loaders are implemented by inheriting from the `Loader` class, and\nimplementing its methods. This loader can then be used by `Stream` to load data\nby passing it via the `custom_loaders={'scheme': CustomLoader}` argument.\n\nThe skeleton of a custom loader looks like:\n\n```python\nfrom tabulator import Loader\n\nclass CustomLoader(Loader):\n  options = []\n\n  def __init__(self, bytes_sample_size, **options):\n      pass\n\n  def load(self, source, mode='t', encoding=None):\n      # load logic\n\nwith Stream(source, custom_loaders={'custom': CustomLoader}) as stream:\n  stream.read()\n```\n\nYou can see examples of how the loaders are implemented by looking in the\n`tabulator.loaders` module.\n\n#### Custom parsers\n\nYou can add support for a new file format by creating a custom parser. Similarly\nto custom loaders, custom parsers are implemented by inheriting from the\n`Parser` class, and implementing its methods. This parser can then be used by\n`Stream` to parse data by passing it via the `custom_parsers={'format':\nCustomParser}` argument.\n\nThe skeleton of a custom parser looks like:\n\n```python\nfrom tabulator import Parser\n\nclass CustomParser(Parser):\n    options = []\n\n    def __init__(self, loader, force_parse, **options):\n        self.__loader = loader\n\n    def open(self, source, encoding=None):\n        # open logic\n\n    def close(self):\n        # close logic\n\n    def reset(self):\n        # reset logic\n\n    @property\n    def closed(self):\n        return False\n\n    @property\n    def extended_rows(self):\n        # extended rows logic\n\nwith Stream(source, custom_parsers={'custom': CustomParser}) as stream:\n  stream.read()\n```\n\nYou can see examples of how parsers are implemented by looking in the\n`tabulator.parsers` module.\n\n#### Custom writers\n\nYou can add support to write files in a specific format by creating a custom\nwriter. The custom writers are implemented by inheriting from the base `Writer`\nclass, and implementing its methods. This writer can then be used by `Stream` to\nwrite data via the `custom_writers={'format': CustomWriter}` argument.\n\nThe skeleton of a custom writer looks like:\n\n```python\nfrom tabulator import Writer\n\nclass CustomWriter(Writer):\n  options = []\n\n  def __init__(self, **options):\n      pass\n\n  def write(self, source, target, headers=None, encoding=None):\n      # write logic\n\nwith Stream(source, custom_writers={'custom': CustomWriter}) as stream:\n  stream.save(target)\n```\n\nYou can see examples of how parsers are implemented by looking in the\n`tabulator.writers` module.\n\n## API Reference\n\n### `cli`\n```python\ncli(source, limit, **options)\n```\nCommand-line interface\n\n```\nUsage: tabulator [OPTIONS] SOURCE\n\nOptions:\n  --headers INTEGER\n  --scheme TEXT\n  --format TEXT\n  --encoding TEXT\n  --limit INTEGER\n  --sheet TEXT/INTEGER (excel)\n  --fill-merged-cells BOOLEAN (excel)\n  --preserve-formatting BOOLEAN (excel)\n  --adjust-floating-point-error BOOLEAN (excel)\n  --table TEXT (sql)\n  --order_by TEXT (sql)\n  --resource TEXT/INTEGER (datapackage)\n  --property TEXT (json)\n  --keyed BOOLEAN (json)\n  --version          Show the version and exit.\n  --help             Show this message and exit.\n```\n\n\n### `Stream`\n```python\nStream(self,\n       source,\n       headers=None,\n       scheme=None,\n       format=None,\n       encoding=None,\n       compression=None,\n       allow_html=False,\n       sample_size=100,\n       bytes_sample_size=10000,\n       ignore_blank_headers=False,\n       ignore_listed_headers=None,\n       ignore_not_listed_headers=None,\n       multiline_headers_joiner=' ',\n       multiline_headers_duplicates=False,\n       force_strings=False,\n       force_parse=False,\n       pick_rows=None,\n       skip_rows=None,\n       pick_fields=None,\n       skip_fields=None,\n       pick_columns=None,\n       skip_columns=None,\n       post_parse=[],\n       custom_loaders={},\n       custom_parsers={},\n       custom_writers={},\n       **options)\n```\nStream of tabular data.\n\nThis is the main `tabulator` class. It loads a data source, and allows you\nto stream its parsed contents.\n\n__Arguments__\n\n\n    source (str):\n        Path to file as ``<scheme>://path/to/file.<format>``.\n        If not explicitly set, the scheme (file, http, ...) and\n        format (csv, xls, ...) are inferred from the source string.\n\n    headers (Union[int, List[int], List[str]], optional):\n        Either a row\n        number or list of row numbers (in case of multi-line headers) to be\n        considered as headers (rows start counting at 1), or the actual\n        headers defined a list of strings. If not set, all rows will be\n        treated as containing values.\n\n    scheme (str, optional):\n        Scheme for loading the file (file, http, ...).\n        If not set, it'll be inferred from `source`.\n\n    format (str, optional):\n        File source's format (csv, xls, ...). If not\n        set, it'll be inferred from `source`. inferred\n\n    encoding (str, optional):\n        Source encoding. If not set, it'll be inferred.\n\n    compression (str, optional):\n        Source file compression (zip, ...). If not set, it'll be inferred.\n\n    pick_rows (List[Union[int, str, dict]], optional):\n        The same as `skip_rows` but it's for picking rows instead of skipping.\n\n    skip_rows (List[Union[int, str, dict]], optional):\n        List of row numbers, strings and regex patterns as dicts to skip.\n        If a string, it'll skip rows that their first cells begin with it e.g. '#' and '//'.\n        To skip only completely blank rows use `{'type': 'preset', 'value': 'blank'}`\n        To try and auto detect the beginning of the table, use `{'type': 'preset', 'value': 'auto'}`\n        To provide a regex pattern use  `{'type': 'regex', 'value': '^#'}`\n        For example: `skip_rows=[1, '# comment', {'type': 'regex', 'value': '^# (regex|comment)'}]`\n\n    pick_fields (str[]):\n        When passed, ignores all columns with headers\n        that the given list DOES NOT include\n\n    skip_fields (str[]):\n        When passed, ignores all columns with headers\n        that the given list includes. If it contains an empty string it will skip\n        empty headers\n\n    sample_size (int, optional):\n        Controls the number of sample rows used to\n        infer properties from the data (headers, encoding, etc.). Set to\n        ``0`` to disable sampling, in which case nothing will be inferred\n        from the data. Defaults to ``config.DEFAULT_SAMPLE_SIZE``.\n\n    bytes_sample_size (int, optional):\n        Same as `sample_size`, but instead\n        of number of rows, controls number of bytes. Defaults to\n        ``config.DEFAULT_BYTES_SAMPLE_SIZE``.\n\n    allow_html (bool, optional):\n        Allow the file source to be an HTML page.\n        If False, raises ``exceptions.FormatError`` if the loaded file is\n        an HTML page. Defaults to False.\n\n    multiline_headers_joiner (str, optional):\n        When passed, it's used to join multiline headers\n        as `<passed-value>.join(header1_1, header1_2)`\n        Defaults to ' ' (space).\n\n    multiline_headers_duplicates (bool, optional):\n        By default tabulator will exclude a cell of a miltilne header from joining\n        if it's exactly the same as the previous seen value in this field.\n        Enabling this option will force duplicates inclusion\n        Defaults to False.\n\n    force_strings (bool, optional):\n        When True, casts all data to strings.\n        Defaults to False.\n\n    force_parse (bool, optional):\n        When True, don't raise exceptions when\n        parsing malformed rows, simply returning an empty value. Defaults\n        to False.\n\n    post_parse (List[function], optional):\n        List of generator functions that\n        receives a list of rows and headers, processes them, and yields\n        them (or not). Useful to pre-process the data. Defaults to None.\n\n    custom_loaders (dict, optional):\n        Dictionary with keys as scheme names,\n        and values as their respective ``Loader`` class implementations.\n        Defaults to None.\n\n    custom_parsers (dict, optional):\n        Dictionary with keys as format names,\n        and values as their respective ``Parser`` class implementations.\n        Defaults to None.\n\n    custom_loaders (dict, optional):\n        Dictionary with keys as writer format\n        names, and values as their respective ``Writer`` class\n        implementations. Defaults to None.\n\n    **options (Any, optional): Extra options passed to the loaders and parsers.\n\n\n\n#### `stream.closed`\nReturns True if the underlying stream is closed, False otherwise.\n\n__Returns__\n\n`bool`: whether closed\n\n\n\n#### `stream.compression`\nStream's compression (\"no\" if no compression)\n\n__Returns__\n\n`str`: compression\n\n\n\n#### `stream.encoding`\nStream's encoding\n\n__Returns__\n\n`str`: encoding\n\n\n\n#### `stream.format`\nPath's format\n\n__Returns__\n\n`str`: format\n\n\n\n#### `stream.fragment`\nPath's fragment\n\n__Returns__\n\n`str`: fragment\n\n\n\n#### `stream.hash`\nReturns the SHA256 hash of the read chunks if available\n\n__Returns__\n\n`str/None`: SHA256 hash\n\n\n\n#### `stream.headers`\nHeaders\n\n__Returns__\n\n`str[]/None`: headers if available\n\n\n\n#### `stream.sample`\nReturns the stream's rows used as sample.\n\nThese sample rows are used internally to infer characteristics of the\nsource file (e.g. encoding, headers, ...).\n\n__Returns__\n\n`list[]`: sample\n\n\n\n#### `stream.scheme`\nPath's scheme\n\n__Returns__\n\n`str`: scheme\n\n\n\n#### `stream.size`\nReturns the BYTE count of the read chunks if available\n\n__Returns__\n\n`int/None`: BYTE count\n\n\n\n#### `stream.source`\nSource\n\n__Returns__\n\n`any`: stream source\n\n\n\n#### `stream.open`\n```python\nstream.open()\n```\nOpens the stream for reading.\n\n__Raises:__\n\n    TabulatorException: if an error\n\n\n\n#### `stream.close`\n```python\nstream.close()\n```\nCloses the stream.\n\n\n#### `stream.reset`\n```python\nstream.reset()\n```\nResets the stream pointer to the beginning of the file.\n\n\n#### `stream.iter`\n```python\nstream.iter(keyed=False, extended=False)\n```\nIterate over the rows.\n\nEach row is returned in a format that depends on the arguments `keyed`\nand `extended`. By default, each row is returned as list of their\nvalues.\n\n__Arguments__\n- __keyed (bool, optional)__:\n        When True, each returned row will be a\n        `dict` mapping the header name to its value in the current row.\n        For example, `[{'name': 'J Smith', 'value': '10'}]`. Ignored if\n        ``extended`` is True. Defaults to False.\n- __extended (bool, optional)__:\n        When True, returns each row as a tuple\n        with row number (starts at 1), list of headers, and list of row\n        values. For example, `(1, ['name', 'value'], ['J Smith', '10'])`.\n        Defaults to False.\n\n__Raises__\n- `exceptions.TabulatorException`: If the stream is closed.\n\n__Returns__\n\n`Iterator[Union[List[Any], Dict[str, Any], Tuple[int, List[str], List[Any]]]]`:\n        The row itself. The format depends on the values of `keyed` and\n        `extended` arguments.\n\n\n\n#### `stream.read`\n```python\nstream.read(keyed=False, extended=False, limit=None)\n```\nReturns a list of rows.\n\n__Arguments__\n- __keyed (bool, optional)__: See :func:`Stream.iter`.\n- __extended (bool, optional)__: See :func:`Stream.iter`.\n- __limit (int, optional)__:\n        Number of rows to return. If None, returns all rows. Defaults to None.\n\n__Returns__\n\n`List[Union[List[Any], Dict[str, Any], Tuple[int, List[str], List[Any]]]]`:\n        The list of rows. The format depends on the values of `keyed`\n        and `extended` arguments.\n\n\n#### `stream.save`\n```python\nstream.save(target, format=None, encoding=None, **options)\n```\nSave stream to the local filesystem.\n\n__Arguments__\n- __target (str)__: Path where to save the stream.\n- __format (str, optional)__:\n        The format the stream will be saved as. If\n        None, detects from the ``target`` path. Defaults to None.\n- __encoding (str, optional)__:\n        Saved file encoding. Defaults to ``config.DEFAULT_ENCODING``.\n- __**options__: Extra options passed to the writer.\n\n__Returns__\n\n`count (int?)`: Written rows count if available\nBuilding index...\nStarted generating documentation...\n\n### `Loader`\n```python\nLoader(self, bytes_sample_size, **options)\n```\nAbstract class implemented by the data loaders\n\nThe loaders inherit and implement this class' methods to add support for a\nnew scheme (e.g. ssh).\n\n__Arguments__\n- __bytes_sample_size (int)__: Sample size in bytes\n- __**options (dict)__: Loader options\n\n\n\n#### `loader.options`\n\n\n#### `loader.load`\n```python\nloader.load(source, mode='t', encoding=None)\n```\nLoad source file.\n\n__Arguments__\n- __source (str)__: Path to tabular source file.\n- __mode (str, optional)__:\n        Text stream mode, `t` (text) or `b` (binary).  Defaults to `t`.\n- __encoding (str, optional)__:\n        Source encoding. Auto-detect by default.\n\n__Returns__\n\n`Union[TextIO, BinaryIO]`: I/O stream opened either as text or binary.\n\n\n### `Parser`\n```python\nParser(self, loader, force_parse, **options)\n```\nAbstract class implemented by the data parsers.\n\nThe parsers inherit and implement this class' methods to add support for a\nnew file type.\n\n__Arguments__\n- __loader (tabulator.Loader)__: Loader instance to read the file.\n- __force_parse (bool)__:\n        When `True`, the parser yields an empty extended\n        row tuple `(row_number, None, [])` when there is an error parsing a\n        row. Otherwise, it stops the iteration by raising the exception\n        `tabulator.exceptions.SourceError`.\n- __**options (dict)__: Loader options\n\n\n\n#### `parser.closed`\nFlag telling if the parser is closed.\n\n__Returns__\n\n`bool`: whether closed\n\n\n\n#### `parser.encoding`\nEncoding\n\n__Returns__\n\n`str`: encoding\n\n\n\n#### `parser.extended_rows`\nReturns extended rows iterator.\n\nThe extended rows are tuples containing `(row_number, headers, row)`,\n\n__Raises__\n- `SourceError`:\n        If `force_parse` is `False` and\n        a row can't be parsed, this exception will be raised.\n        Otherwise, an empty extended row is returned (i.e.\n        `(row_number, None, [])`).\n\nReturns:\n    Iterator[Tuple[int, List[str], List[Any]]]:\n        Extended rows containing\n        `(row_number, headers, row)`, where `headers` is a list of the\n        header names (can be `None`), and `row` is a list of row\n        values.\n\n\n\n#### `parser.options`\n\n\n#### `parser.open`\n```python\nparser.open(source, encoding=None)\n```\nOpen underlying file stream in the beginning of the file.\n\nThe parser gets a byte or text stream from the `tabulator.Loader`\ninstance and start emitting items.\n\n__Arguments__\n- __source (str)__: Path to source table.\n- __encoding (str, optional)__: Source encoding. Auto-detect by default.\n\n__Returns__\n\n    None\n\n\n\n#### `parser.close`\n```python\nparser.close()\n```\nCloses underlying file stream.\n\n\n#### `parser.reset`\n```python\nparser.reset()\n```\nResets underlying stream and current items list.\n\nAfter `reset()` is called, iterating over the items will start from the beginning.\n\n### `Writer`\n```python\nWriter(self, **options)\n```\nAbstract class implemented by the data writers.\n\nThe writers inherit and implement this class' methods to add support for a\nnew file destination.\n\n__Arguments__\n- __**options (dict)__: Writer options.\n\n\n\n#### `writer.options`\n\n\n#### `writer.write`\n```python\nwriter.write(source, target, headers, encoding=None)\n```\nWrites source data to target.\n\n__Arguments__\n- __source (str)__: Source data.\n- __target (str)__: Write target.\n- __headers (List[str])__: List of header names.\n- __encoding (str, optional)__: Source file encoding.\n\n__Returns__\n\n`count (int?)`: Written rows count if available\n\n\n### `validate`\n```python\nvalidate(source, scheme=None, format=None)\n```\nCheck if tabulator is able to load the source.\n\n__Arguments__\n- __source (Union[str, IO])__: The source path or IO object.\n- __scheme (str, optional)__: The source scheme. Auto-detect by default.\n- __format (str, optional)__: The source file format. Auto-detect by default.\n\n__Raises__\n- `SchemeError`: The file scheme is not supported.\n- `FormatError`: The file format is not supported.\n\n__Returns__\n\n`bool`: Whether tabulator is able to load the source file.\n\n\n### `TabulatorException`\n```python\nTabulatorException()\n```\nBase class for all tabulator exceptions.\n\n\n### `SourceError`\n```python\nSourceError()\n```\nThe source file could not be parsed correctly.\n\n\n### `SchemeError`\n```python\nSchemeError()\n```\nThe file scheme is not supported.\n\n\n### `FormatError`\n```python\nFormatError()\n```\nThe file format is unsupported or invalid.\n\n\n### `EncodingError`\n```python\nEncodingError()\n```\nEncoding error\n\n\n### `CompressionError`\n```python\nCompressionError()\n```\nCompression error\n\n\n### `IOError`\n```python\nIOError()\n```\nLocal loading error\n\n\n### `LoadingError`\n```python\nLoadingError()\n```\nLocal loading error\n\n\n### `HTTPError`\n```python\nHTTPError()\n```\nRemote loading error\n\n## Contributing\n\n> The project follows the [Open Knowledge International coding standards](https://github.com/okfn/coding-standards).\n\nRecommended way to get started is to create and activate a project virtual environment.\nTo install package and development dependencies into active environment:\n\n```bash\n$ make install\n```\n\nTo run tests with linting and coverage:\n\n```bash\n$ make test\n```\n\nTo run tests without Internet:\n\n```\n$ pytest -m 'not remote\n```\n\n## Changelog\n\nHere described only breaking and the most important changes. The full changelog and documentation for all released versions could be found in nicely formatted [commit history](https://github.com/frictionlessdata/tabulator-py/commits/master).\n\n#### v1.53\n\n- Add support for raw_html extraction in html parser (#341)\n\n#### v1.52\n\n- Published stream.dialect (works only for csv, for now)\n\n#### v1.51\n\n- Added experimental table discovery options\n\n#### v1.50\n\n- Ensure that headers is always a list of strings\n\n#### v1.49\n\n- Added `workbook_cache` argument for XLSX formats\n\n#### v1.48\n\n- Published `stream.hashing_algorithm` property\n\n#### v1.47\n\n- Added `hashing_algorithm` parameter\n\n#### v1.46\n\n- Fixed multiline headers merging\n- Introduced a `multiline_headers_duplicates` flag\n\n#### v1.45\n\n- HTML format: adds support for empty selector (#321)\n\n#### v1.44\n\n- Exposed `stream.compression`\n\n#### v1.43\n\n- Exposed `stream.source`\n\n#### v1.42\n\n- Exposed format option to the CLI\n\n#### v1.41\n\n- Implemented a `pick_rows` parameter (opposite to `skip_rows`)\n\n#### v1.40\n\n- Implemented `stream.save()` returning count of written rows\n\n#### v1.39\n\n- Implemented JSON writer (#311)\n\n#### v1.38\n\n- Use `chardet` for encoding detection by default. For `cchardet`: `pip install tabulator[cchardet]`. Due to a great deal of problems caused by `ccharted` for non-Linux/Conda installations we're returning back to using `chardet` by default.\n\n#### v1.37\n\n- Raise IOError/HTTPError even a not-existent file has a bad format (#304)\n\n#### v1.36\n\n- Implemented `blank` preset for `skip_rows` (#302)\n\n#### v1.35\n\n- Added `skip/pick_columns` aliases for (#293)\n\n#### v1.34\n\n- Added `multiline_headers_joiner` argument (#291)\n\n#### v1.33\n\n- Added support for regex patterns in `skip_rows` (#290)\n\n#### v1.32\n\n- Added ability to skip columns (#293)\n\n#### v1.31\n\n- Added `xlsx` writer\n- Added `html` reader\n\n#### v1.30\n\n- Added `adjust_floating_point_error` parameter to the `xlsx` parser\n\n#### v1.29\n\n- Implemented the `stream.size` and `stream.hash` properties\n\n#### v1.28\n\n- Added SQL writer\n\n#### v1.27\n\n- Added `http_timeout` argument for the `http/https` format\n\n#### v1.26\n\n- Added `stream.fragment` field showing e.g. Excel sheet's or DP resource's name\n\n#### v1.25\n\n- Added support for the `s3` file scheme (data loading from AWS S3)\n\n#### v1.24\n\n- Added support for compressed file-like objects\n\n#### v1.23\n\n- Added a setter for the `stream.headers` property\n\n#### v1.22\n\n- The `headers` parameter will now use the first not skipped row if the `skip_rows` parameter is provided and there are comments on the top of a data source (see #264)\n\n#### v1.21\n\n- Implemented experimental `preserve_formatting` for xlsx\n\n#### v1.20\n\n- Added support for specifying filename in zip source\n\n#### v1.19\n\nUpdated behaviour:\n- For `ods` format the boolean, integer and datetime native types are detected now\n\n#### v1.18\n\nUpdated behaviour:\n- For `xls` format the boolean, integer and datetime native types are detected now\n\n#### v1.17\n\nUpdated behaviour:\n- Added support for Python 3.7\n\n#### v1.16\n\nNew API added:\n- `skip_rows` support for an empty string to skip rows with an empty first column\n\n#### v1.15\n\nNew API added:\n- Format will be extracted from URLs like `http://example.com?format=csv`\n\n#### v1.14\n\nUpdated behaviour:\n- Now `xls` booleans will be parsed as booleans not integers\n\n#### v1.13\n\nNew API added:\n- The `skip_rows` argument now supports negative numbers to skip rows starting from the end\n\n#### v1.12\n\nUpdated behaviour:\n- Instead of raising an exception, a `UserWarning` warning will be emitted if an option isn't recognized.\n\n#### v1.11\n\nNew API added:\n- Added `http_session` argument for the `http/https` format (it uses `requests` now)\n- Added support for multiline headers: `headers` argument accept ranges like `[1,3]`\n\n#### v1.10\n\nNew API added:\n- Added support for compressed files i.e. `zip` and `gz` on Python3\n- The `Stream` constructor now accepts a `compression` argument\n- The `http/https` scheme now accepts a `http_stream` flag\n\n#### v1.9\n\nImproved behaviour:\n- The `headers` argument allows to set the order for keyed sources and cherry-pick values\n\n#### v1.8\n\nNew API added:\n- Formats `XLS/XLSX/ODS` supports sheet names passed via the `sheet` argument\n- The `Stream` constructor accepts an `ignore_blank_headers` option\n\n#### v1.7\n\nImproved behaviour:\n- Rebased `datapackage` format on `datapackage@1` library\n\n#### v1.6\n\nNew API added:\n- Argument `source` for the `Stream` constructor can be a `pathlib.Path`\n\n#### v1.5\n\nNew API added:\n- Argument `bytes_sample_size` for the `Stream` constructor\n\n#### v1.4\n\nImproved behaviour:\n- Updated encoding name to a canonical form\n\n#### v1.3\n\nNew API added:\n- `stream.scheme`\n- `stream.format`\n- `stream.encoding`\n\nPromoted provisional API to stable API:\n- `Loader` (custom loaders)\n- `Parser` (custom parsers)\n- `Writer` (custom writers)\n- `validate`\n\n#### v1.2\n\nImproved behaviour:\n- Autodetect common CSV delimiters\n\n#### v1.1\n\nNew API added:\n- Added `fill_merged_cells` option to `xls/xlsx` formats\n\n#### v1.0\n\nNew API added:\n- published `Loader/Parser/Writer` API\n- Added `Stream` argument `force_strings`\n- Added `Stream` argument `force_parse`\n- Added `Stream` argument `custom_writers`\n\nDeprecated API removal:\n- removed `topen` and `Table` - use `Stream` instead\n- removed `Stream` arguments `loader/parser_options` - use `**options` instead\n\nProvisional API changed:\n- Updated the `Loader/Parser/Writer` API - please use an updated version\n\n#### v0.15\n\nProvisional API added:\n- Unofficial support for `Stream` arguments `custom_loaders/parsers`\n\n\n[stream.py]: tabulator/stream.py\n[examples-dir]: examples \"Examples\"\n[requests-session]: https://docs.puthon-requests.org/en/master/user/advanced/#session-objects\n[pydoc-csv]: https://docs.python.org/3/library/csv.html#dialects-and-formatting-parameters \"Python CSV options\"\n[sqlalchemy]: https://www.sqlalchemy.org/\n[tdp]: https://frictionlessdata.io/specs/tabular-data-package/ \"Tabular Data Package\"\n[tabulator.exceptions]: tabulator/exceptions.py \"Tabulator Exceptions\"\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Consistent interface for stream reading and writing tabular data (csv/xls/json/etc)",
    "version": "1.54.3",
    "project_urls": {
        "Homepage": "https://github.com/akariv/tabulator-py"
    },
    "split_keywords": [
        "frictionless",
        "data"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e4b05449ceacb94f82e238b84e39cf09096f6084942f43ccc0b8754d92f583d9",
                "md5": "ae3cf1a57b4acdbbde18089efbb0d207",
                "sha256": "3bdceeb06e128d5f794b4c2d48e5788a9c9b8a8c98cf918db6f47bfc29b08fd4"
            },
            "downloads": -1,
            "filename": "dataflows_tabulator-1.54.3-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ae3cf1a57b4acdbbde18089efbb0d207",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 72176,
            "upload_time": "2024-03-24T13:58:14",
            "upload_time_iso_8601": "2024-03-24T13:58:14.094396Z",
            "url": "https://files.pythonhosted.org/packages/e4/b0/5449ceacb94f82e238b84e39cf09096f6084942f43ccc0b8754d92f583d9/dataflows_tabulator-1.54.3-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "32d70a540880fb7fe287227fa55a98e0f1aeff13a9785c6c77cbae66e2ce922f",
                "md5": "bb680bce3513406a5699b88f9b341df9",
                "sha256": "c697990bf91d16fb2ca1885cd665608a60c6c2c68d4d5e07609b455a93b20352"
            },
            "downloads": -1,
            "filename": "dataflows-tabulator-1.54.3.tar.gz",
            "has_sig": false,
            "md5_digest": "bb680bce3513406a5699b88f9b341df9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 83857,
            "upload_time": "2024-03-24T13:58:15",
            "upload_time_iso_8601": "2024-03-24T13:58:15.722165Z",
            "url": "https://files.pythonhosted.org/packages/32/d7/0a540880fb7fe287227fa55a98e0f1aeff13a9785c6c77cbae66e2ce922f/dataflows-tabulator-1.54.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-24 13:58:15",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "akariv",
    "github_project": "tabulator-py",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": true,
    "lcname": "dataflows-tabulator"
}
        
Elapsed time: 2.12565s