codewarnab commented on code in PR #41186:
URL: https://github.com/apache/beam/pull/41186#discussion_r4670022015
##########
sdks/python/apache_beam/yaml/yaml_io.py:
##########
@@ -99,6 +104,260 @@ def write_to_text(pcoll, path: str):
lambda x: str(getattr(x, sole_field_name))) | beam.io.WriteToText(path)
+def read_from_csv(
+ path: str,
+ *,
+ sep: str = ',',
+ comment: Optional[str] = None,
+ filename_column: Optional[str] = None,
+ error_handling: Optional[Mapping[str, Any]] = None,
+ **kwargs):
+ """Reads comma-separated values (csv) files into a PCollection of rows.
+
+ Without ``error_handling``, this is ``apache_beam.io.ReadFromCsv``.
+
+ With ``error_handling``, each record is parsed on its own, and records
+ that fail to parse go to the error output instead of failing the pipeline.
+ Each error row has the source file path and the raw record text.
+ The column types come from the first 100 records of the first file.
+
+ Args:
+ path (str): The file path to read from. The path can contain glob
+ characters such as ``*`` and ``?``.
+ sep (str): The field delimiter.
+ comment (str): Lines that start with this character are skipped.
+ filename_column (str): If set, the name of a column to add to each
+ record, containing the path of the source file.
+ error_handling: If specified, should be a mapping giving an output into
+ which to emit records that failed to parse, as described at
+ https://beam.apache.org/documentation/sdks/yaml-errors/
+ """
+ if not error_handling:
+ return beam_io.ReadFromCsv(
+ path,
+ sep=sep,
+ comment=comment,
+ filename_column=filename_column,
+ **kwargs)
+ if kwargs:
+ raise ValueError(
+ f'ReadFromCsv does not support {sorted(kwargs)} with error_handling.')
+
+ def sample(handle):
+ return pd.read_csv(
+ handle,
+ sep=sep,
+ comment=comment,
+ nrows=_SAMPLE_SIZE,
+ on_bad_lines='skip')
+
+ def parse_record(header, record, dtypes):
+ columns = list(dtypes)
+ fields = pd.read_csv(
+ io.StringIO(record), header=None, sep=sep, comment=comment, dtype=str)
+ if len(fields.columns) != len(columns):
+ raise ValueError(
+ f'Expected {len(columns)} fields, got {len(fields.columns)}.')
+ df = pd.read_csv(
+ io.StringIO(header + record), sep=sep, comment=comment, dtype=dtypes)
+ if list(df.columns) != columns:
+ raise ValueError(
+ f'The file header {list(df.columns)} does not match {columns}.')
+ return df
+
+ def parse_file(lines, proxy):
+ dtypes = proxy.dtypes.drop(filename_column, errors='ignore').to_dict()
Review Comment:
You're right, sorry I missed that. The tests always set `filename_column`,
so this case never ran. Fixed in 10ca9616ac3819d4a4ebdf88da2fa4e4187fb9a6, and
added a test that reads a CSV without `filename_column`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]