Skip to content

File rules

File rules

Rules to read (extract) dataframes from files and write (load) them to files.

Importing the rules

The rules are implemented by each backend. Import them from the package of the backend you use, e.g. from etlrules.backends.pandas import ReadCSVFileRule (or etlrules.backends.polars, etlrules.backends.dask, etlrules.backends.pyarrow). The arguments and the behaviour are the same in all the backends, unless stated otherwise.

ReadCSVFileRule

Reads one or multiple csv files from a directory and persists it as a dataframe for subsequent rules to operate on.

Basic usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# reads a file data.csv and persists it as the main output of the rule
rule = ReadCSVFileRule("data.csv", "/home/myuser/")
rule.apply(data)

# reads a file test_data.csv and persists it as the input_data named output
# other rules can specify input_data as their named_input to operate on it
rule = ReadCSVFileRule("test_data.csv", "/home/myuser/", named_output="input_data")
rule.apply(data)

# extracts all files starting with data followed by 4 digits and concatenate them
# e.g. data1234.csv, data5678.csv, etc.
rule = ReadCSVFileRule("data[0-9]{4}.csv", "/home/myuser/", regex=True, named_output="input_data")
rule.apply(data)

Parameters:

Name Type Description Default
file_name str

The name of the csv file to load. The format will be inferred from the extension of the file. A simple text csv file will be inferred from the .csv extension. The extensions like .zip, .gz, .bz2, .xz will extract a single compressed csv file from the given input compressed file. file_name can also be a regular expression (specify regex=True in that case). The reader will find all the files in the file_dir directory that match the regular expression and extract all those csv file and concatenate them into a single dataframe. For example, file_name=".*.csv", file_dir=".", regex=True will extract all the files with the .csv extension from the current directory. It can also be an URI (e.g. https://example.com/mycsv.csv)

required
file_dir Optional[str]

The file directory where the file_name is located. When file_name is a regular expression and the regex parameter is True, file_dir is the directory that is inspected for any files that match the regular expression. Optional. For files it defaults to . (ie the current directory). Ignored for URIs.

None
regex bool

When True, the file_name is interpreted as a regular expression. Defaults to False.

False
separator str

The single character to be used as separator in the csv file. Defaults to , (comma).

','
header bool

When True, the first line is interpreted as the header and the column names are extracted from it. When False, the first line is part of the data and the columns will have names like 0, 1, 2, etc. Defaults to True.

True
skip_header_rows Optional[int]

Optional number of rows to skip at the top of the file, before the header.

None
named_output Optional[str]

Give the output of this rule a name so it can be used by another rule as a named input. Optional. When not set, the result of this rule will be available as the main output. When set to a name (string), the result will be available as that named output.

None
name Optional[str]

Give the rule a name. Optional. Named rules are more descriptive as to what they're trying to do/the intent.

None
description Optional[str]

Describe in detail what the rules does, how it does it. Optional. Together with the name, the description acts as the documentation of the rule.

None
strict bool

When set to True, the rule does a stricter valiation. Default: True

True

Raises:

Type Description
IOError

raised when the file is not found.

ReadParquetFileRule

Reads one or multiple parquet files from a directory and persists it as a dataframe for subsequent rules to operate on.

Basic usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# reads a file data.csv and persists it as the main output of the rule
rule = ReadParquetFileRule("data.parquet", "/home/myuser/")
rule.apply(data)

# reads a file test_data.parquet and persists it as the input_data named output
# other rules can specify input_data as their named_input to operate on it
rule = ReadParquetFileRule("test_data.parquet", "/home/myuser/", named_output="input_data")
rule.apply(data)

# reads all the files with the .parquet extension from the home dir of myuser and
# concatenates them into a single dataframe
rule = ReadParquetFileRule(".*\.parquet", "/home/myuser/", named_output="input_data")
rule.apply(data)

# reads only the A,B,C columns from the file data.csv file
rule = ReadParquetFileRule("data.parquet", "/home/myuser/", columns=["A", "B", "C"])
rule.apply(data)

# reads only those rows where column A is greater than 10 and column B is True
rule = ReadParquetFileRule("data.parquet", "/home/myuser/", filters=[["A", ">=", 10], ["B", "==", True]])
rule.apply(data)

Parameters:

Name Type Description Default
file_name str

The name of the parquet file to load. The format will be inferred from the extension of the file. file_name can also be a regular expression (specify regex=True in that case). The reader will find all the files in the file_dir directory that match the regular expression and extract all those parquet file and concatenate them into a single dataframe. For example, file_name=".*.parquet", file_dir=".", regex=True will extract all the files with the .parquet extension from the current directory.

required
file_dir str

The file directory where the file_name is located. When file_name is a regular expression and the regex parameter is True, file_dir is the directory that is inspected for any files that match the regular expression. Defaults to . (ie the current directory).

'.'
regex bool

When True, the file_name is interpreted as a regular expression. Defaults to False.

False
columns Optional[Sequence[str]]

A subset of the columns in the parquet file to load.

None
filters Optional[Union[List[Tuple], List[List[Tuple]]]]

A list of filters to apply to filter the rows returned. Rows which do not match the filter conditions will be removed from scanned data. When passed as a List[List[Tuple]], the conditions in the inner lists are AND-end together with the top level condition OR-ed together. Eg: ((cond1 AND cond2...) OR (cond3 AND cond4...)...) When passed as a List[Tuple], the conditions are AND-ed together. E.g.: cond1 AND cond2 AND cond3... Each condition is specified as a tuple of 3 elements: (column, operation, value). Column is the name of a column in the input dataframe. Operation is one of: "==", "=", ">", ">=", "<", "<=", "!=", "in", "not in". Value is a scalar value, int, float, string, etc. When the operation is in or not in, the value must be a list, tuple or set of values.

None
named_output Optional[str]

Give the output of this rule a name so it can be used by another rule as a named input. Optional. When not set, the result of this rule will be available as the main output. When set to a name (string), the result will be available as that named output.

None
name Optional[str]

Give the rule a name. Optional. Named rules are more descriptive as to what they're trying to do/the intent.

None
description Optional[str]

Describe in detail what the rules does, how it does it. Optional. Together with the name, the description acts as the documentation of the rule.

None
strict bool

When set to True, the rule does a stricter valiation. Default: True

True

Raises:

Type Description
IOError

raised when the file is not found.

ValueError

raised if filters are specified but the format is incorrect.

MissingColumnError

raised if a column is specified in columns or filters but it doesn't exist in the input dataframe.

Note

The parquet file can be compressed in which case the compression will be inferred from the file. The following compression algorithms are supported: "snappy", "gzip", "brotli", "lz4", "zstd".

ReadJSONFileRule

Reads one or multiple JSON lines files and persists them as a dataframe for subsequent rules to operate on.

The files must be in the JSON lines format (also known as NDJSON): one JSON object per line, each object being a row with the columns as keys. For example:

1
2
{"Id": 1, "Name": "Mike", "Joined": "2023-05-19"}
{"Id": 2, "Name": "Anna"}

Missing keys (and null values) are missing values (NA) in the result.

Basic usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# reads a file data.json and persists it as the main output of the rule
rule = ReadJSONFileRule("data.json", "/home/myuser/")
rule.apply(data)

# reads all the files events_YYYYMMDD.json.gz in a directory and concatenates them
rule = ReadJSONFileRule(r"events_\d{8}\.json\.gz", "/home/myuser/", regex=True, named_output="events")
rule.apply(data)

# reads a file, converting the Id column to int32 (rather than relying on the type inference)
rule = ReadJSONFileRule("data.json", "/home/myuser/", column_types={"Id": "int32", "Name": "string"})
rule.apply(data)

Parameters:

Name Type Description Default
file_name str

The name of the JSON lines file to load. The extensions .gz, .bz2, .xz and .zip indicate a compressed file (.zip archives must contain a single file). file_name can also be a regular expression (specify regex=True in that case). The reader will find all the files in the file_dir directory that match the regular expression and extract all those files and concatenate them into a single dataframe. It can also be an URI (e.g. https://example.com/data.json)

required
file_dir Optional[str]

The file directory where the file_name is located. When file_name is a regular expression and the regex parameter is True, file_dir is the directory that is inspected for any files that match the regular expression. Optional. For files it defaults to . (ie the current directory). Ignored for URIs.

None
regex bool

When True, the file_name is interpreted as a regular expression. Defaults to False.

False
column_types Optional[Mapping[str, str]]

A mapping of column names and their types. Optional. The types are inferred from the data, but the inference can differ between backends (and the type of a column which only has missing values can't be inferred): specifying the types makes the result the same in all the backends. The supported types are: int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, string and boolean.

None
named_output Optional[str]

Give the output of this rule a name so it can be used by another rule as a named input. Optional. When not set, the result of this rule will be available as the main output. When set to a name (string), the result will be available as that named output.

None
name Optional[str]

Give the rule a name. Optional. Named rules are more descriptive as to what they're trying to do/the intent.

None
description Optional[str]

Describe in detail what the rules does, how it does it. Optional. Together with the name, the description acts as the documentation of the rule.

None
strict bool

When set to True, the rule does a stricter validation. Default: True

True

Raises:

Type Description
IOError

raised when the file is not found.

UnsupportedTypeError

raised if any of the column_types are not supported.

MissingColumnError

raised in strict mode only if a column in column_types is not in the data. In non-strict mode, the missing columns are ignored.

Note

The values which are JSON strings are read as strings, including dates and times: use StrToDateTimeRule to convert them to datetime values.

Note

Nested JSON objects and arrays are read as each backend represents them: python dicts and lists with the pandas and dask backends, structs and lists with the polars and pyarrow backends.

WriteCSVFileRule

Writes an existing dataframe to a csv file (optionally compressed) on disk.

The rule is a final rule, which means it produces no additional outputs, it takes any of the existing outputs and writes it to disk.

Basic usage:

1
2
3
4
5
6
7
# writes a file data.csv and persists the main output of the previous rule to it
rule = WriteCSVFileRule("data.csv", "/home/myuser/")
rule.apply(data)

# writes a file test_data.csv and persists the dataframe named input_data into it
rule = WriteCSVFileRule("test_data.csv", "/home/myuser/", named_input="input_data")
rule.apply(data)

Parameters:

Name Type Description Default
file_name str

The name of the csv file to write to disk. It will be written in the directory specified by the file_dir parameter.

required
file_dir str

The file directory where the file_name should be written. Defaults to . (ie the current directory).

'.'
separator str

The single character to separate values in the csv file. Defaults to , (comma).

','
header bool

When True, the first line will contain the columns separated by the separator. When False, the columns will not be written and the first line contains data. Defaults to True.

True
compression Optional[str]

Compress the csv file using a supported compression algorithms. Optional. When the compression is specified, the file_name must end with the extension associate with that compression format. The following options are supported: zip - file_name must end with .zip (e.g. output.csv.zip), will produced a zipped csv file gzip - file_name must end with .gz (e.g. output.csv.gz), will produced a gzipped csv file bz2 - file_name must end with .bz2 (e.g. output.csv.bz2), will produced a bzipped csv xz - file_name must end with .xz (e.g. output.csv.xz), will produced a xz-compressed csv file

None
named_input Optional[str]

Select by name the dataframe to write from the input data. Optional. When not specified, the main output of the previous rule will be written.

None
name Optional[str]

Give the rule a name. Optional. Named rules are more descriptive as to what they're trying to do/the intent.

None
description Optional[str]

Describe in detail what the rules does, how it does it. Optional. Together with the name, the description acts as the documentation of the rule.

None
strict bool

When set to True, the rule does a stricter valiation. Default: True.

True

WriteParquetFileRule

Writes an existing dataframe to a parquet file on disk.

The rule is a final rule, which means it produces no additional outputs, it takes any of the existing outputs and writes it to disk.

Basic usage:

1
2
3
4
5
6
7
# writes a file data.parquet and persists the main output of the previous rule to it
rule = WriteParquetFileRule("data.parquet", "/home/myuser/")
rule.apply(data)

# writes a file test_data.parquet and persists the dataframe named input_data into it
rule = WriteParquetFileRule("test_data.parquet", "/home/myuser/", named_input="input_data")
rule.apply(data)

Parameters:

Name Type Description Default
file_name str

The name of the parquet file to write to disk. It will be written in the directory specified by the file_dir parameter.

required
file_dir str

The file directory where the file_name should be written. Defaults to . (ie the current directory).

'.'
compression Optional[str]

Compress the parquet file using a supported compression algorithms. Optional. The following compression algorithms are supported: "snappy", "gzip", "brotli", "lz4", "zstd".

None
named_input Optional[str]

Select by name the dataframe to write from the input data. Optional. When not specified, the main output of the previous rule will be written.

None
name Optional[str]

Give the rule a name. Optional. Named rules are more descriptive as to what they're trying to do/the intent.

None
description Optional[str]

Describe in detail what the rules does, how it does it. Optional. Together with the name, the description acts as the documentation of the rule.

None
strict bool

When set to True, the rule does a stricter valiation. Default: True.

True

WriteJSONFileRule

Writes an existing dataframe to a JSON lines file (optionally compressed) on disk.

Each row is written as a JSON object on its own line (also known as NDJSON), with the columns as keys. The rule is a final rule, which means it produces no additional outputs, it takes any of the existing outputs and writes it to disk.

Basic usage:

1
2
3
4
5
6
7
# writes a file data.json and persists the main output of the previous rule to it
rule = WriteJSONFileRule("data.json", "/home/myuser/")
rule.apply(data)

# writes a gzip compressed file with the dataframe named input_data
rule = WriteJSONFileRule("data.json.gz", "/home/myuser/", compression="gzip", named_input="input_data")
rule.apply(data)

Parameters:

Name Type Description Default
file_name str

The name of the JSON lines file to write to disk. It will be written in the directory specified by the file_dir parameter.

required
file_dir str

The file directory where the file_name should be written. Defaults to . (ie the current directory).

'.'
compression Optional[str]

Compress the file using a supported compression algorithm. Optional. When the compression is specified, the file_name must end with the extension associated with that compression format. The following options are supported: zip - file_name must end with .zip (e.g. output.json.zip), will produce a zipped file gzip - file_name must end with .gz (e.g. output.json.gz), will produce a gzipped file bz2 - file_name must end with .bz2 (e.g. output.json.bz2), will produce a bzipped file xz - file_name must end with .xz (e.g. output.json.xz), will produce a xz-compressed file

None
named_input Optional[str]

Which dataframe to use as the input. Optional. When not set, the input is taken from the main output. Set it to a string value, the name of an output dataframe of a previous rule.

None
name Optional[str]

Give the rule a name. Optional. Named rules are more descriptive as to what they're trying to do/the intent.

None
description Optional[str]

Describe in detail what the rules does, how it does it. Optional. Together with the name, the description acts as the documentation of the rule.

None
strict bool

When set to True, the rule does a stricter validation. Default: True

True
Note

Missing values are written as null. Datetime values are written as ISO 8601 strings with microseconds (e.g. 2023-05-19T10:30:45.000000) in all the backends. The files are written in UTF-8.