File I/O, JSON and Data
open System.IO
File.WriteAllText("notes.txt", "Hello\n")
File.AppendAllText("notes.txt", "More\n")
let text = File.ReadAllText "notes.txt"
let lines = File.ReadAllLines "notes.txt" // string[]
File.ReadLines "big.txt" |> Seq.filter (fun l -> l <> "") |> Seq.length // lazy streaming
File.Exists "notes.txt", Directory.Exists "data"
Directory.CreateDirectory "out" |> ignore
Directory.GetFiles(".", "*.fs") |> Array.iter (printfn "%s")
Path.Combine("data", "file.csv"), Path.GetExtension "a.txt"
// Async file I/O
task {
let! content = File.ReadAllTextAsync "notes.txt"
do! File.WriteAllTextAsync("copy.txt", content)
} |> ignore
// JSON with System.Text.Json + FSharp.SystemTextJson (supports unions, options, records)
open System.Text.Json
open System.Text.Json.Serialization
type Person = { Name: string; Age: int; Email: string option }
let options = JsonSerializerOptions(WriteIndented = true)
options.Converters.Add(JsonFSharpConverter())
let json = JsonSerializer.Serialize({ Name = "Ana"; Age = 30; Email = None }, options)
let back = JsonSerializer.Deserialize<Person>(json, options)
// CSV, JSON, XML with FSharp.Data type providers (Module 40), Thoth.Json (Fable-
…