Reading and Writing CSV files#

Arrow provides a fast CSV reader allowing ingestion of external datato create Arrow Tables or a stream of Arrow RecordBatches.

Reading CSV files#

Data in a CSV file can either be read in as a single Arrow Table usingTableReader or streamed as RecordBatches usingStreamingReader. SeeTradeoffs for adiscussion of the tradeoffs between the two methods.

Both these readers require anarrow::io::InputStream instancerepresenting the input file. Their behavior can be customized using acombination ofReadOptions,ParseOptions, andConvertOptions.

TableReader#

#include"arrow/csv/api.h"{// ...arrow::io::IOContextio_context=arrow::io::default_io_context();std::shared_ptr<arrow::io::InputStream>input=...;autoread_options=arrow::csv::ReadOptions::Defaults();autoparse_options=arrow::csv::ParseOptions::Defaults();autoconvert_options=arrow::csv::ConvertOptions::Defaults();// Instantiate TableReader from input stream and optionsautomaybe_reader=arrow::csv::TableReader::Make(io_context,input,read_options,parse_options,convert_options);if(!maybe_reader.ok()){// Handle TableReader instantiation error...}std::shared_ptr<arrow::csv::TableReader>reader=*maybe_reader;// Read table from CSV fileautomaybe_table=reader->Read();if(!maybe_table.ok()){// Handle CSV read error// (for example a CSV syntax error or failed type conversion)}std::shared_ptr<arrow::Table>table=*maybe_table;}

StreamingReader#

#include"arrow/csv/api.h"{// ...arrow::io::IOContextio_context=arrow::io::default_io_context();std::shared_ptr<arrow::io::InputStream>input=...;autoread_options=arrow::csv::ReadOptions::Defaults();autoparse_options=arrow::csv::ParseOptions::Defaults();autoconvert_options=arrow::csv::ConvertOptions::Defaults();// Instantiate StreamingReader from input stream and optionsautomaybe_reader=arrow::csv::StreamingReader::Make(io_context,input,read_options,parse_options,convert_options);if(!maybe_reader.ok()){// Handle StreamingReader instantiation error...}std::shared_ptr<arrow::csv::StreamingReader>reader=*maybe_reader;// Set aside a RecordBatch pointer for re-use while streamingstd::shared_ptr<RecordBatch>batch;while(true){// Attempt to read the first RecordBatcharrow::Statusstatus=reader->ReadNext(&batch);if(!status.ok()){// Handle read error}if(batch==NULL){// Handle end of filebreak;}// Do something with the batch}}

Tradeoffs#

The choice between usingTableReader orStreamingReader will ultimately depend on the use casebut there are a few tradeoffs to be aware of:

  1. Memory usage:TableReader loads all of the datainto memory at once and, depending on the amount of data, may requireconsiderably more memory thanStreamingReader whichonly loads oneRecordBatch at a time. This is likely to bethe most significant tradeoff for users.

  2. Speed: When reading the entire contents of a CSV,TableReader will tend to be faster thanStreamingReader because it makes better use ofavailable cores. SeePerformance for moredetails.

  3. Flexibility:StreamingReader might be consideredless flexible thanTableReader because it performs typeinference only on the first block that’s read in, after which point the typesare frozen and any data in subsequent blocks that cannot be converted tothose types will cause an error. Note that this can be remedied either bysettingReadOptions::block_size to a large enough value or by usingConvertOptions::column_types to set the desired data typesexplicitly.

Writing CSV files#

A CSV file is written to aOutputStream.

#include<arrow/csv/api.h>{// Oneshot write// ...std::shared_ptr<arrow::io::OutputStream>output=...;autowrite_options=arrow::csv::WriteOptions::Defaults();if(WriteCSV(table,write_options,output.get()).ok()){// Handle writer error...}}{// Write incrementally// ...std::shared_ptr<arrow::io::OutputStream>output=...;autowrite_options=arrow::csv::WriteOptions::Defaults();automaybe_writer=arrow::csv::MakeCSVWriter(output,schema,write_options);if(!maybe_writer.ok()){// Handle writer instantiation error...}std::shared_ptr<arrow::ipc::RecordBatchWriter>writer=*maybe_writer;// Write batches...if(!writer->WriteRecordBatch(*batch).ok()){// Handle write error...}if(!writer->Close().ok()){// Handle close error...}if(!output->Close().ok()){// Handle file close error...}}

Note

The writer does not yet support all Arrow types.

Column names#

There are three possible ways to infer column names from the CSV file:

  • By default, the column names are read from the first row in the CSV file

  • IfReadOptions::column_names is set, it forces the columnnames in the table to these values (the first row in the CSV file isread as data)

  • IfReadOptions::autogenerate_column_names is true, column nameswill be autogenerated with the pattern “f0”, “f1”… (the first row in theCSV file is read as data)

Column selection#

By default, Arrow reads all columns in the CSV file. You can narrow theselection of columns with theConvertOptions::include_columnsoption. If some columns inConvertOptions::include_columnsare missing from the CSV file, an error will be emitted unlessConvertOptions::include_missing_columns is true, in which casethe missing columns are assumed to contain all-null values.

Interaction with column names#

If bothReadOptions::column_names andConvertOptions::include_columns are specified,theReadOptions::column_names are assumed to map to CSV columns,andConvertOptions::include_columns is a subset of those columnnames that will part of the Arrow Table.

Data types#

By default, the CSV reader infers the most appropriate data type for eachcolumn. Type inference considers the following data types, in order:

It is possible to override type inference for select columns by settingtheConvertOptions::column_types option. Explicit data typescan be chosen from the following list:

  • Null

  • All Integer types

  • Float32 and Float64

  • Decimal128

  • Boolean

  • Date32 and Date64

  • Time32 and Time64

  • Timestamp

  • Binary and Large Binary

  • String and Large String (with optional UTF8 input validation)

  • Fixed-Size Binary

  • Duration (numeric strings matching the schema unit, e.g., “60000” for duration[ms])

  • Dictionary with index type Int32 and value type one of the following:Binary, String, LargeBinary, LargeString, Int32, UInt32, Int64, UInt64,Float32, Float64, Decimal128

Other data types do not support conversion from CSV values and will error out.

Dictionary inference#

If type inference is enabled andConvertOptions::auto_dict_encodeis true, the CSV reader first tries to convert string-like columns to adictionary-encoded string-like array. It switches to a plain string-likearray when the threshold inConvertOptions::auto_dict_max_cardinalityis reached.

Timestamp inference/parsing#

If type inference is enabled, the CSV reader first tries to interpretstring-like columns as timestamps. If all rows have some zone offset(e.g.Z or+0100), even if the offsets are inconsistent, then theinferred type will be UTC timestamp. If no rows have a zone offset, then theinferred type will be timestamp without timezone. A mix of rows with/withoutoffsets will result in a string column.

If the type is explicitly specified as a timestamp with/without timezone, thenthe reader will error on values without/with zone offsets in that column. Notethat this means it isn’t currently possible to have the reader parse a columnof timestamps without zone offsets as local times in a particular timezone;instead, parse the column as timestamp without timezone, then convert thevalues afterwards using theassume_timezone compute function.

Specified Type

Input CSV

Result Type

(inferred)

2021-01-01T00:00:00

timestamp[s]

2021-01-01T00:00:00Z

timestamp[s, UTC]

2021-01-01T00:00:00+0100

2021-01-01T00:00:002021-01-01T00:00:00Z

string

timestamp[s]

2021-01-01T00:00:00

timestamp[s]

2021-01-01T00:00:00Z

(error)

2021-01-01T00:00:00+0100

2021-01-01T00:00:002021-01-01T00:00:00Z

timestamp[s, UTC]

2021-01-01T00:00:00

(error)

2021-01-01T00:00:00Z

timestamp[s, UTC]

2021-01-01T00:00:00+0100

2021-01-01T00:00:002021-01-01T00:00:00Z

(error)

timestamp[s,America/New_York]

2021-01-01T00:00:00

(error)

2021-01-01T00:00:00Z

timestamp[s,America/New_York]

2021-01-01T00:00:00+0100

2021-01-01T00:00:002021-01-01T00:00:00Z

(error)

Nulls#

Null values are recognized from the spellings stored inConvertOptions::null_values. TheConvertOptions::Defaults()factory method will initialize a number of conventional null spellings suchasN/A.

Character encoding#

CSV files are expected to be encoded in UTF8. However, non-UTF8 datais accepted for Binary columns.

Write Options#

The format of written CSV files can be customized viaWriteOptions.Currently few options are available; more will be added in future releases.

Performance#

By default,TableReader will parallelize reads in order toexploit all CPU cores on your machine. You can change this setting inReadOptions::use_threads. A reasonable expectation is at least100 MB/s per core on a performant desktop or laptop computer (measured insource CSV bytes, not target Arrow data bytes).