CSV Parser
The F# CSV Type Provider is built on top of an efficient CSV parser written in F#. There's also a simple API that can be used to access values dynamically.
When working with well-defined CSV documents, it is easier to use the type provider, but in a more dynamic scenario or when writing quick and simple scripts, the parser might be a simpler option.
Loading CSV documents
To load a sample CSV document, we first need to reference the FSharp.Data
package.
open FSharp.Data
The FSharp.Data
namespace contains the CsvFile type that provides two static methods
for loading data. The CsvFile.Parse method can be used if we have the data in a string
value.
The CsvFile.Load method allows reading the data from a file or from a web resource (and there's
also an asynchronous CsvFile.AsyncLoad version). The following sample calls CsvFile.Load with a URL that
points to a live CSV file on the Yahoo finance web site:
// Download the stock prices
let msft =
CsvFile
.Load(__SOURCE_DIRECTORY__ + "/../data/MSFT.csv")
.Cache()
// Print the prices in the HLOC format
for row in msft.Rows |> Seq.truncate 10 do
printfn "HLOC: (%s, %s, %s)" (row.GetColumn "High") (row.GetColumn "Low") (row.GetColumn "Date")
|
Note that unlike CsvProvider
, CsvFile works in streaming mode for performance reasons, which means
that CsvFile.Rows can only be iterated once. If you need to iterate multiple times, use the CsvFile.Cache method,
but please note that this will increase memory usage and should not be used in large datasets.
Using CSV extensions
Now we look at a number of extensions that become available after opening the CsvExtensions namespace. Once opened, we can write:
-
row?column
uses the dynamic operator to obtain the column value namedcolumn
; alternatively, you can also use an indexerrow.[column]
. value.AsBoolean()
returns the value as boolean if it is eithertrue
orfalse
(see StringExtensions.AsBoolean)-
value.AsInteger()
returns the value as integer if it is numeric and can be converted to an integer;value.AsInteger64()
,value.AsDecimal()
andvalue.AsFloat()
behave similarly. -
value.AsDateTime()
returns the value as aDateTime
value using either the ISO 8601 format, or using the\/Date(...)\/
JSON format containing number of milliseconds since 1/1/1970. -
value.AsDateTimeOffset()
parses the string as aDateTimeOffset
value using either the ISO 8601 format, or using the\/Date(...[+/-]offset)\/
JSON format containing number of milliseconds since 1/1/1970, [+/-] the 4 digit offset. Example-\/Date(1231456+1000)\/
. value.AsTimeSpan()
parses the string as aTimeSpan
value.value.AsGuid()
returns the value as aGuid
value.
Methods that may need to parse a numeric value or date (such as AsFloat
and
AsDateTime
) receive an optional culture parameter.
The following example shows how to process the sample previous CSV sample using these extensions:
open FSharp.Data.CsvExtensions
for row in msft.Rows |> Seq.truncate 10 do
printfn "HLOC: (%f, %M, %O)" (row.["High"].AsFloat()) (row?Low.AsDecimal()) (row?Date.AsDateTime())
|
Transforming CSV files
In addition to reading, CsvFile also has support for transforming CSV files. The operations
available are CsvFile.Filter, Take
, TakeWhile
, Skip
, SkipWhile
, and Truncate
. After transforming
you can save the results by using one of the overloads of the Save
method. You can choose different
separator and quote characters when saving.
// Saving the first 10 stock prices where the closing price is higher than the opening price in TSV format:
msft
.Filter(fun row -> row?Close.AsFloat() > row?Open.AsFloat())
.Truncate(10)
.SaveToString('\t')
|
Related articles
- CSV Type Provider - discusses F# type provider that provides type-safe access to CSV data
- API Reference: CsvFile
- API Reference: CsvRow
- API Reference: CsvExtensions
namespace FSharp
--------------------
namespace Microsoft.FSharp
namespace FSharp.Data
--------------------
namespace Microsoft.FSharp.Data
<summary> Represents a CSV file. The lines are read on demand from <c>reader</c>. Columns are delimited by one of the chars passed by <c>separators</c> (defaults to just <c>,</c>), and to escape the separator chars, the <c>quote</c> character will be used (defaults to <c>"</c>). If <c>hasHeaders</c> is true (the default), the first line read by <c>reader</c> will not be considered part of data. If <c>ignoreErrors</c> is true (the default is false), rows with a different number of columns from the header row (or the first row if headers are not present) will be ignored. The first <c>skipRows</c> lines will be skipped. </summary>
<summary> The rows with data </summary>
member CsvRow.GetColumn: index: int -> string
<summary> Provides the dynamic operator for getting column values by name from CSV rows </summary>