用于读取和写入表格数据的流接口(csv/xls/json等)
项目描述
dataflows-tabulator-py
一个用于读取和写入表格数据(csv/xls/json等)的库。
[重要通知] 这是对存档的 tabulator-py 存储库的分支。原始存储库不再维护。此分支由Adam Kariv维护。
功能
- 支持大多数常见表格格式: CSV,XLS,ODS,JSON,Google Sheets,SQL等。见以下完整列表。
- 加载本地和远程数据: 支持 HTTP,FTP 和 S3。
- 内存使用量低: 仅保留当前行在内存中,因此可以处理大型数据集。
- 支持压缩文件: 使用 ZIP 或 GZIP 算法。
- 可扩展: 您可以添加对自定义文件格式和加载器的支持(例如 FTP)。
内容
入门指南
安装
$ pip install tabulator
在CLI上运行
Tabulator提供了一个简单的命令行界面(CLI),称为tabulator
,用于读取表格数据。例如:
$ tabulator https://github.com/frictionlessdata/tabulator-py/raw/4c1b3943ac98be87b551d87a777d0f7ca4904701/data/table.csv.gz
id,name
1,english
2,中国人
您可以通过运行tabulator --help
来查看所有支持选项。
在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, ..]
您可以在examples
目录中找到其他示例。
文档
在以下部分,我们将通过一些使用示例来介绍这个库。所有示例均在Python 3.6上测试过,但也应该在Python 3.3+上运行良好。
与流一起工作
Stream
类表示一个表格流。它将文件路径作为source
参数。例如:
<scheme>://path/to/file.<format>
它使用此路径来确定文件格式(例如CSV或XLS)和方案(例如HTTP或postgresql)。它还支持从URL(如http://example.com?format=csv
)中提取格式。如果需要,您也可以显式定义这些。
让我们试试。首先,我们创建一个包含CSV文件路径的Stream
对象。
import tabulator
stream = tabulator.Stream('data.csv')
到此为止,文件尚未被读取。让我们打开流以便我们可以读取内容。
try:
stream.open()
except tabulator.TabulatorException as e:
pass # Handle exception
这将打开底层数据流,读取一小部分以检测文件编码,并准备要读取的数据。我们在这里捕获tabulator.TabulatorException
,以防出现错误。
现在我们可以读取文件内容了。要遍历每一行,我们做
for row in stream.iter():
print(row) # [value1, value2, ...]
stream.iter()
方法将返回每行数据作为值的列表。如果您愿意,也可以调用stream.iter(keyed=True)
,它将返回一个以列名为键的字典。无论如何,此方法一次只保留一行在内存中。这意味着它可以处理大文件而不会消耗太多内存。
如果您想读取整个文件,请使用stream.read()
。它接受与stream.iter()
相同的参数,但一次返回所有行。
stream.reset()
rows = stream.read()
请注意,在读取行之前,我们调用了stream.reset()
。这是因为tabulator内部只保留对文件当前位置的指针。如果我们不重置此指针,我们将从停止的位置开始读取。例如,如果我们再次运行stream.read()
,我们将得到一个空列表,因为内部文件指针位于文件末尾(因为我们已经全部读取了)。根据文件位置,可能需要重新下载文件以回滚(例如,当文件从网络加载时)。
完成后,使用以下方式关闭流:
stream.close()
整个示例看起来像这样:
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()
它可以重写为使用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
这是首选方式,因为Python会自动关闭流,即使在过程中抛出了异常。
完整的API文档作为Stream源代码中的docstrings提供。
标题
默认情况下,tabulator认为所有文件行都是值(即没有标题)。
with Stream([['name', 'age'], ['Alex', 21]]) as stream:
stream.headers # None
stream.read() # [['name', 'age'], ['Alex', 21]]
如果您有一行标题,可以使用带有其行号(从1开始)的headers
参数。
# Integer
with Stream([['name', 'age'], ['Alex', 21]], headers=1) as stream:
stream.headers # ['name', 'age']
stream.read() # [['Alex', 21]]
您也可以传递字符串列表来显式定义标题
with Stream([['Alex', 21]], headers=['name', 'age']) as stream:
stream.headers # ['name', 'age']
stream.read() # [['Alex', 21]]
Tabulator还支持xls
和xlsx
格式的多行标题。
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
参数指定文件编码(例如utf-8
和latin1
)。
with Stream(source, encoding='latin1') as stream:
stream.read()
如果此参数未设置,Tabulator将尝试从数据中推断它。如果在加载文件时遇到UnicodeDecodeError
,请尝试将编码设置为utf-8
。
压缩(仅Python3)
Tabulator支持ZIP和GZIP压缩方法。默认情况下,它将从文件名推断
with Stream('http://example.com/data.csv.zip') as stream:
stream.read()
您也可以显式设置它
with Stream('data.csv.ext', compression='gz') as stream:
stream.read()
选项
- filename:要处理的zip文件中的文件名(默认是第一个文件)
允许HTML
如果 Stream
类检测到 HTML 内容,则会抛出 tabulator.exceptions.FormatError
异常。这有助于避免在 HTML 页面中尝试加载 CSV 文件等相对常见的错误,例如在 GitHub 上。
您可以使用 allow_html
选项来禁用此行为。
with Stream(source_with_html, allow_html=True) as stream:
stream.read() # no exception on open
样本大小
为了检测文件的标题,并运行其他检查,例如验证文件不包含 HTML,Tabulator 会在 stream.open()
方法中读取一行样本。此数据可通过 stream.sample
属性访问。使用的行数可以通过 sample_size
参数定义(默认为 100)。
with Stream(two_rows_source, sample_size=1) as stream:
stream.sample # only first row
stream.read() # first and second rows
您可以通过将 sample_size
设置为零来禁用此功能。这样,在 stream.open()
期间不会读取任何数据。
字节样本大小
Tabulator 需要读取文件的一部分以推断其编码。由 bytes_sample_size
参数控制将读取多少字节进行此检测(默认为 10000)。
source = 'data/special/latin1.csv'
with Stream(source) as stream:
stream.encoding # 'iso8859-2'
您可以通过将 bytes_sample_size
设置为零来禁用此功能,在这种情况下,它将使用机器区域的默认编码。
忽略空标题
当设置为 True
时,Tabulator 将忽略具有空标题的列(默认为 False
)。
# 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_blank_headers
。它根据相应的列名从数据中删除任意列。
# 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'},
]
强制字符串
当设置为 True
时,所有行的值都将转换为字符串(默认为 False
)。None
值将转换为空字符串。
# 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']]
强制解析
当设置为 True
时,在解析格式不正确的行时不会抛出异常,而是简单地返回空行。否则,当行无法解析时,Tabulator 会抛出 tabulator.exceptions.SourceError
。默认为 False
。
# 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]]
跳过行
要跳过的行号和/或字符串的列表。如果它是字符串,则将跳过所有以它开头的行(例如,'#' 和 '//')。如果是空字符串,则将跳过所有以空列开头的行。
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]]
如果将 headers
参数也设置为整数,则它将使用第一个未跳过的行作为标题。
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]]
解析后
一组函数,可以在解析后过滤或转换行。这些函数接收包含行号、标题列表和行值列表的 extended_rows
。然后处理行,并根据需要进行修改或丢弃。
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]]
这些函数按顺序应用,作为一个简单的数据管道。在上面的示例中,multiply_by_two
只看到 skip_odd_rows
产生的行。
关键字和扩展行
stream.iter()
和 stream.read()
方法接受 keyed
和 extended
标志参数来修改返回行的行为。
默认情况下,每行都作为单元格值的列表返回。
with Stream([['name', 'age'], ['Alex', 21]]) as stream:
stream.read() # [['Alex', 21]]
使用 keyed=True
,行将作为字典返回,将列名映射到行中的值。
with Stream([['name', 'age'], ['Alex', 21]]) as stream:
stream.read(keyed=True) # [{'name': 'Alex', 'age': 21}]
使用 extended=True
,行将作为 (row_number, headers, row)
的元组返回,其中 row_number
是当前行号(从 1 开始),headers
是包含标题名称的列表,row
是包含行值的列表。
with Stream([['name', 'age'], ['Alex', 21]]) as stream:
stream.read(extended=True) # (1, ['name', 'age'], ['Alex', 21])
支持的方案
s3
它从 AWS S3 加载数据。对于私有文件,您应提供由 boto3
库支持的凭证,例如相应的环境变量。有关配置 boto3
的更多信息,请参阅 配置 boto3
。
stream = Stream('s3://bucket/data.csv')
选项
- s3_endpoint_url - 要使用的端点 URL。默认为
https://s3.amazonaws.com
。对于复杂用例,例如在数据包上运行goodtables
,此选项可以作为环境变量S3_ENDPOINT_URL
提供。
file
默认方案,本地文件系统中的文件。
stream = Stream('data.csv')
http/https/ftp/ftps
在Python 2中,由于底层库的限制,
tabulator
无法流式传输远程数据源。整个数据源将被加载到内存中。在Python 3中,没有这样的问题,远程文件可以进行流式传输。
stream = Stream('https://example.com/data.csv')
选项
- http_session - 一个
requests.Session
对象。更多信息请参阅requests文档。 - http_stream - 当可能时启用或禁用HTTP流式传输(默认启用)。如果您希望将整个文件预加载到内存中,请禁用它。
- http_timeout - 此超时将用于
requests
会话构造。
stream
源是一个类似文件的Python对象。
with open('data.csv') as fp:
stream = Stream(fp)
text
源是一个包含表格数据的字符串。必须显式设置scheme
和format
,因为无法推断它们。
stream = Stream(
'name,age\nJohn, 21\n',
scheme='text',
format='csv'
)
支持的文件格式
在本节中,我们将描述支持的文件格式以及相应的配置选项和操作。某些格式仅支持读取操作,而其他格式则支持读取和写入。
csv(读取 & 写入)
stream = Stream('data.csv', delimiter=',')
选项
它支持Python CSV库中的所有选项。有关更多信息,请参阅它们的文档。
xls/xlsx(读取 & 写入)
Tabulator无法流式传输
xls
文件,所以整个文件将被加载到内存中。对于xlsx
文件,支持流式传输。
stream = Stream('data.xls', sheet=1)
选项
- sheet:工作表名称或编号(从1开始)。
- workbook_cache:一个空字典,用于处理工作簿缓存。如果提供,Tabulator将使用
source: tmpfile_path
对来填充字典,对于远程工作簿。每个工作簿只下载一次,所有临时文件将在进程退出时被删除。默认:None - fill_merged_cells:如果为
True
,则将取消合并并填充所有合并的单元格,使用可见值填充。启用此选项后,解析器无法流式传输数据,并将整个文档加载到内存中。 - preserve_formatting:如果为
True
,它将尝试保留数字和日期单元格的文本格式,并将其作为字符串返回,以反映它在电子表格中的外观(实验性) - adjust_floating_point_error:如果为
True
,它将纠正Excel关于浮点数的行为
ods(只读)
此格式默认不包含在包中。要使用它,请使用带有
ods
额外信息的Tabulator进行安装:$ pip install tabulator[ods]
源应该是有效的Open Office文档。
stream = Stream('data.ods', sheet=1)
选项
- sheet:工作表名称或编号(从1开始)
gsheet(只读)
一个公开可访问的Google电子表格。
stream = Stream('https://docs.google.com/spreadsheets/d/<id>?usp=sharing')
stream = Stream('https://docs.google.com/spreadsheets/d/<id>edit#gid=<gid>')
sql(读取 & 写入)
支持sqlalchemy的任何数据库URL。
stream = Stream('postgresql://name:pass@host:5432/database', table='data')
选项
- table (必需):数据库表名称
- order_by:用于行排序的SQL表达式(例如,
name DESC
)
数据包(只读)
此格式默认不包含在包中。您可以通过使用
pip install tabulator[datapackage]
安装Tabulator来启用它。
一个表格数据包。
stream = Stream('datapackage.json', resource=1)
选项
- resource:资源名称或索引(从0开始)
inline(只读)
可以是列表的列表,也可以是列表的字典,将列名称映射到相应的值。
stream = Stream([['name', 'age'], ['John', 21], ['Alex', 33]])
stream = Stream([{'name': 'John', 'age': 21}, {'name': 'Alex', 'age': 33}])
json(读取 & 写入)
包含列表的列表或列名称映射到相应值的字典列表的JSON文档(有关示例,请参阅inline
格式)。
stream = Stream('data.json', property='key1.key2')
选项
- property:包含表格数据的属性的JSON路径。例如,考虑JSON
{"response": {"data": [...]}}
,则property
应设置为response.data
。 - keyed(写入):保存为数组数组(默认)或数组字典(键控)。
ndjson(只读)
stream = Stream('data.ndjson')
tsv(只读)
stream = Stream('data.tsv')
html(只读)
默认情况下不包含此格式。要使用它,请安装带有
html
扩展的tabulator
:$ pip install tabulator[html]
HTML 文档内的 HTML 表格元素。
支持简单表格(无合并单元格)和任何合法组合的 td、th、tbody 和 thead 元素。
通常需要显式指定 format='html'
,因为网页 URL 并不总是使用 .html
扩展名。
stream = Stream('http://example.com/some/page.aspx', format='html' selector='.content .data table#id1', raw_html=True)
选项
-
selector:用于指定要提取哪个
table
元素的 CSS 选择器。默认为table
,它取文档中的第一个table
元素。如果为空,则假定整个页面是要提取的表格(与某些 Excel 格式一起使用很有用)。 -
raw_html:False(默认)以提取每个单元格的文本内容。True 以返回未修改的内部 html。
自定义文件源和格式
Tabulator 以可扩展性为目标编写,允许您添加对新表格文件格式、方案(例如 ssh)和写入器(例如 MongoDB)的支持。有三个组件允许这样做
- 加载器
- 从某个位置(例如 ssh)加载流。
- 解析器
- 解析某种格式的表格数据流(例如 xls)。
- 写入器
- 将表格数据写入某个目的地(例如 MongoDB)。
在本节中,我们将了解如何编写自定义类以扩展这些组件中的任何组件。
自定义加载器
您可以通过创建自定义加载器来添加对新的方案(例如 ssh)的支持。自定义加载器通过继承 Loader
类并实现其方法来实现。然后,此加载器可以通过将 custom_loaders={'scheme': CustomLoader}
参数传递给 Stream
来使用它加载数据。
自定义加载器的结构如下所示
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()
您可以通过查看 tabulator.loaders
模块来查看加载器的实现示例。
自定义解析器
您可以通过创建自定义解析器来添加对新的文件格式的支持。与自定义加载器类似,自定义解析器通过继承 Parser
类并实现其方法来实现。然后,此解析器可以通过将 custom_parsers={'format': CustomParser}
参数传递给 Stream
来使用它解析数据。
自定义解析器的结构如下所示
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()
您可以通过查看 tabulator.parsers
模块来查看解析器的实现示例。
自定义写入器
您可以通过创建自定义写入器来添加对特定格式的文件的支持。自定义写入器通过继承基类 Writer
并实现其方法来实现。然后,此写入器可以通过将 custom_writers={'format': CustomWriter}
参数传递给 Stream
来使用它写入数据。
自定义写入器的结构如下所示
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)
您可以通过查看 tabulator.writers
模块来查看写入器的实现示例。
API参考
cli
cli(source, limit, **options)
命令行界面
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
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)
表格数据流。
这是主要的 tabulator
类。它加载数据源,并允许您流式传输其解析内容。
参数
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
如果底层流已关闭,则返回 True,否则返回 False。
返回
bool
:是否关闭
stream.compression
流的压缩(如果没有压缩则为 "no")
返回
str
:压缩
stream.encoding
流的编码
返回
str
:编码
stream.format
路径的格式
返回
str
:格式
stream.fragment
路径的片段
返回
str
:片段
stream.hash
如果可用,则返回读取块的计算 SHA256 哈希。
返回
str/None
:SHA256 哈希
stream.headers
标题
返回
str[]/None
:如果可用,则包含标题
stream.sample
返回用作样本的流的行。
这些示例行用于内部推断源文件的特性(例如编码、头信息等)。
返回
list[]
:示例
stream.scheme
路径的方案
返回
str
:方案
stream.size
如果可用,返回读取块的字节计数
返回
int/None
:字节计数
stream.source
源
返回
any
:流源
stream.open
stream.open()
打开流以供读取。
引发
TabulatorException: if an error
stream.close
stream.close()
关闭流。
stream.reset
stream.reset()
将流指针重置为文件开头。
stream.iter
stream.iter(keyed=False, extended=False)
遍历行。
每行以依赖于参数 keyed
和 extended
的格式返回。默认情况下,每行返回为其值的列表。
参数
- keyed (bool, 可选):当为 True 时,每个返回的行将是一个将头名称映射到当前行中值的
dict
。例如,[{'name': 'J Smith', 'value': '10'}]
。如果extended
为 True,则忽略。默认为 False。 - extended (bool, 可选):当为 True 时,返回每行作为包含行号(从 1 开始)、列头列表和行值列表的元组。例如,
(1, ['name', 'value'], ['J Smith', '10'])
。默认为 False。
引发
exceptions.TabulatorException
:如果流已关闭。
返回
Iterator[Union[List[Any], Dict[str, Any], Tuple[int, List[str], List[Any]]]]
:行本身。格式取决于 keyed
和 extended
参数的值。
stream.read
stream.read(keyed=False, extended=False, limit=None)
返回行列表。
参数
- keyed (bool, 可选):见 :func:
Stream.iter
。 - extended (bool, 可选):见 :func:
Stream.iter
。 - limit (int, 可选):要返回的行数。如果为 None,则返回所有行。默认为 None。
返回
List[Union[List[Any], Dict[str, Any], Tuple[int, List[str], List[Any]]]]
:行列表。格式取决于 keyed
和 extended
参数的值。
stream.save
stream.save(target, format=None, encoding=None, **options)
将流保存到本地文件系统。
参数
- target (str):保存流的路径。
- format (str, 可选):流将被保存的格式。如果为 None,则从
target
路径检测。默认为 None。 - encoding (str, 可选):保存文件的编码。默认为
config.DEFAULT_ENCODING
。 - **options:传递给写入器的额外选项。
返回
count (int?)
:如果可用,则写入的行数 ... 正在生成文档...
Loader
Loader(self, bytes_sample_size, **options)
数据加载器实现的可抽象类
加载器继承并实现此类的功能以添加对新方案(例如 ssh)的支持。
参数
- bytes_sample_size (int):字节样本大小
- **options (dict):加载器选项
loader.options
loader.load
loader.load(source, mode='t', encoding=None)
加载源文件。
参数
- source (str):表格源文件的路径。
- mode (str, 可选):文本流模式,
t
(文本)或b
(二进制)。默认为t
。 - encoding (str, 可选):源编码。默认自动检测。
返回
Union[TextIO, BinaryIO]
:以文本或二进制方式打开的 I/O 流。
Parser
Parser(self, loader, force_parse, **options)
数据解析器实现的可抽象类
解析器继承并实现此类的功能以添加对新文件类型的支持。
参数
- loader (tabulator.Loader):用于读取文件的加载器实例。
- force_parse (bool):当
True
时,解析器在解析行时遇到错误时产生一个空的扩展行元组(row_number, None, [])
。否则,通过引发异常tabulator.exceptions.SourceError
停止迭代。 - **options (dict):加载器选项
parser.closed
指示解析器是否关闭的标志。
返回
bool
:是否关闭
parser.encoding
编码
返回
str
:编码
parser.extended_rows
返回扩展行的迭代器。
扩展行是包含 (row_number, headers, row)
的元组,
引发
SourceError
:如果force_parse
为False
且无法解析行,则引发此异常。否则,返回一个空的扩展行(即(row_number, None, [])
)。
返回: Iterator[Tuple[int, List[str], List[Any]]]: 扩展行,包含(row_number, headers, row)
,其中headers
是头名称的列表(可以是None
),row
是行值的列表。
parser.options
parser.open
parser.open(source, encoding=None)
在文件开头打开底层文件流。
解析器从tabulator.Loader
实例获取字节或文本流并开始发出项目。
参数
- source (str):源表路径。
- encoding (str, 可选):源编码。默认自动检测。
返回
None
parser.close
parser.close()
关闭底层文件流。
parser.reset
parser.reset()
重置底层流和当前项目列表。
在调用reset()
之后,对项目的迭代将从开头开始。
Writer
Writer(self, **options)
由数据编写器实现的抽象类。
编写器继承并实现此类的方法,以添加对新文件目标的支持。
参数
- **options (dict):编写器选项。
writer.options
writer.write
writer.write(source, target, headers, encoding=None)
将源数据写入目标。
参数
- source (str):源数据。
- target (str):写入目标。
- headers (List[str]):头名称列表。
- encoding (str, optional):源文件编码。
返回
count (int?)
:如果可用,则写入的行数
validate
validate(source, scheme=None, format=None)
检查tabulator是否能够加载源。
参数
- source (Union[str, IO]):源路径或IO对象。
- scheme (str, optional):源方案。默认情况下自动检测。
- format (str, optional):源文件格式。默认情况下自动检测。
引发
SchemeError
:文件方案不受支持。FormatError
:文件格式不受支持或不正确。
返回
bool
:tabulator是否能够加载源文件。
TabulatorException
TabulatorException()
所有tabulator异常的基类。
SourceError
SourceError()
源文件无法正确解析。
SchemeError
SchemeError()
文件方案不受支持。
FormatError
FormatError()
文件格式不受支持或不正确。
EncodingError
EncodingError()
编码错误
CompressionError
CompressionError()
压缩错误
IOError
IOError()
本地加载错误
LoadingError
LoadingError()
本地加载错误
HTTPError
HTTPError()
远程加载错误
贡献
推荐的开始方法是创建并激活项目虚拟环境。要将包和开发依赖项安装到活动环境中
$ make install
运行带有linting和覆盖率测试
$ make test
在没有互联网的情况下运行测试
$ pytest -m 'not remote
变更日志
这里仅描述了破坏性和最重要的更改。所有发布版本的完整更改日志和文档可以在格式良好的提交历史记录中找到。
v1.53
- 在HTML解析器中添加对raw_html提取的支持 (#341)
v1.52
- 发布stream.dialect(目前仅适用于csv)
v1.51
- 添加实验性表格发现选项
v1.50
- 确保headers始终是字符串列表
v1.49
- 为XLSX格式添加workbook_cache参数
v1.48
- 发布stream.hashing_algorithm属性
v1.47
- 添加hashing_algorithm参数
v1.46
- 修复多行标题合并
- 引入了multiline_headers_duplicates标志
v1.45
- HTML格式:添加对空选择器的支持 (#321)
v1.44
- 公开stream.compression
v1.43
- 公开stream.source
v1.42
- 将格式选项公开到CLI
v1.41
- 实现了pick_rows参数(与skip_rows相反)
v1.40
- 实现了stream.save()返回写入的行数
v1.39
- 实现了JSON编写器 (#311)
v1.38
- 默认情况下使用chardet进行编码检测。对于cchardet:
pip install tabulator[cchardet]
。由于ccharted在非Linux/Conda安装中引起的大量问题,我们已恢复使用chardet作为默认值。
v1.37
- 即使不存在的文件格式不正确,也会引发IOError/HTTPError (#304)
v1.36
- 实现了blank预置用于skip_rows (#302)
版本1.35
- 添加了
skip/pick_columns
别名(#293)
版本1.34
- 添加了
multiline_headers_joiner
参数(#291)
版本1.33
- 在
skip_rows
中添加了对正则表达式的支持(#290)
版本1.32
- 添加了跳过列的功能(#293)
版本1.31
- 添加了
xlsx
写入器 - 添加了
html
读取器
版本1.30
- 在
xlsx
解析器中添加了adjust_floating_point_error
参数
版本1.29
- 实现了
stream.size
和stream.hash
属性
版本1.28
- 添加了 SQL 写入器
版本1.27
- 为
http/https
格式添加了http_timeout
参数
版本1.26
- 添加了显示例如 Excel 工作表或 DP 资源名称的
stream.fragment
字段
版本1.25
- 添加了对
s3
文件方案的支持(从 AWS S3 加载数据)
版本1.24
- 添加了对压缩文件对象的支持
版本1.23
- 添加了
stream.headers
属性的设置器
版本1.22
- 如果提供
skip_rows
参数且数据源顶部有注释,则headers
参数现在将使用第一个未跳过的行(见 #264)
版本1.21
- 实现了 xlsx 的实验性
preserve_formatting
版本1.20
- 添加了对在 zip 源中指定文件名的支持
版本1.19
更新了行为
- 对于
ods
格式,现在可以检测到布尔型、整型和日期时间原生类型
版本1.18
更新了行为
- 对于
xls
格式,现在可以检测到布尔型、整型和日期时间原生类型
版本1.17
更新了行为
- 添加了对 Python 3.7 的支持
版本1.16
添加了新的 API
- 对空字符串添加了
skip_rows
支持,以跳过第一列空行的行
版本1.15
添加了新的 API
- 将从类似
http://example.com?format=csv
的 URL 中提取格式
版本1.14
更新了行为
- 现在
xls
布尔值将解析为布尔值而不是整数值
版本1.13
添加了新的 API
skip_rows
参数现在支持负数以跳过从末尾开始的行
版本1.12
更新了行为
- 如果选项不被识别,则现在将发出
UserWarning
警告而不是抛出异常
版本1.11
添加了新的 API
- 为
http/https
格式添加了http_session
参数(现在使用requests
) - 添加了对多行标题的支持:
headers
参数接受范围,例如[1,3]
版本1.10
添加了新的 API
- 添加了对压缩文件的支持,即 Python3 上的
zip
和gz
Stream
构造函数现在接受一个compression
参数http/https
方案现在接受一个http_stream
标志
版本1.9
改进了行为
- 现在
headers
参数允许为键控源设置顺序并选择值
版本1.8
添加了新的 API
- 格式
XLS/XLSX/ODS
支持通过sheet
参数传递的工作表名称 Stream
构造函数接受一个ignore_blank_headers
选项
版本1.7
改进了行为
- 将
datapackage
格式基于datapackage@1
库重置
版本1.6
添加了新的 API
Stream
构造函数的source
参数可以是pathlib.Path
版本1.5
添加了新的 API
Stream
构造函数的bytes_sample_size
参数
版本1.4
改进了行为
- 更新了编码名称到规范形式
版本1.3
添加了新的 API
stream.scheme
stream.format
stream.encoding
将临时 API 提升至稳定 API
Loader
(自定义加载器)Parser
(自定义解析器)Writer
(自定义写入器)validate
版本1.2
改进了行为
- 自动检测常见的 CSV 分隔符
版本1.1
添加了新的 API
- 为
xls/xlsx
格式添加了fill_merged_cells
选项
版本1.0
添加了新的 API
- 发布了
Loader/Parser/Writer
API - 添加了
Stream
参数force_strings
- 添加了
Stream
参数force_parse
- 添加了
Stream
参数custom_writers
弃用了 API
- 删除了
topen
和Table
- 使用Stream
代替 - 删除了
Stream
参数loader/parser_options
- 使用**options
代替
临时 API 已更改
- 更新了
Loader/Parser/Writer
API - 请使用更新版本
版本0.15
添加了临时 API
- 对
Stream
参数和custom_loaders/parsers
的非官方支持
项目详情
下载文件
下载适用于您平台的文件。如果您不确定该选择哪个,请了解有关安装包的更多信息。
源代码分发
构建分发
dataflows-tabulator-1.54.3.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | c697990bf91d16fb2ca1885cd665608a60c6c2c68d4d5e07609b455a93b20352 |
|
MD5 | bb680bce3513406a5699b88f9b341df9 |
|
BLAKE2b-256 | 32d70a540880fb7fe287227fa55a98e0f1aeff13a9785c6c77cbae66e2ce922f |
dataflows_tabulator-1.54.3-py2.py3-none-any.whl的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 3bdceeb06e128d5f794b4c2d48e5788a9c9b8a8c98cf918db6f47bfc29b08fd4 |
|
MD5 | ae3cf1a57b4acdbbde18089efbb0d207 |
|
BLAKE2b-256 | e4b05449ceacb94f82e238b84e39cf09096f6084942f43ccc0b8754d92f583d9 |