F# file I/O
last modified December 3, 2026
In this article we read and write files in F#.
F# uses the .NET classes in the System.IO namespace. The
static File class reads or writes a whole file in one call,
which is enough for most small files. For large files and for writing
piece by piece there are streams: a
StreamReader reads text a line at a time and a
StreamWriter writes it. A relative file name refers to the
current working directory, the directory from which the program is run.
Writing and reading a file
File.WriteAllText creates a file, or replaces an existing
one, and writes a string into it. File.ReadAllText reads the
whole file back into a string.
open System.IO
let text = "Pack a lunch.\nCheck the tyres.\n"
File.WriteAllText("todo.txt", text)
let content = File.ReadAllText "todo.txt"
printf "%s" content
printfn "%d characters" content.Length
The script writes two lines into todo.txt and reads them
back.
File.WriteAllText("todo.txt", text)
The method opens the file, writes the text in UTF-8 and closes the file.
The \n line breaks are written as they are; .NET does not
change them on any system.
printf "%s" content
The content already ends with a line break, so it is printed with
printf. The cat command shows that the file is
really on the disk.
λ dotnet fsi whole.fsx Pack a lunch. Check the tyres. 31 characters λ cat todo.txt Pack a lunch. Check the tyres.
Lines
Text files are usually processed line by line.
File.WriteAllLines writes a collection of strings, each
followed by a line break, and File.ReadAllLines returns an
array of lines without the line breaks.
open System.IO
let planets = [ "Mercury"; "Venus"; "Earth"; "Mars" ]
File.WriteAllLines("planets.txt", planets)
let lines = File.ReadAllLines "planets.txt"
printfn "%d lines" lines.Length
lines
|> Array.iteri (fun i line -> printfn "%d. %s" (i + 1) line)
A list of planets is written to a file and read back as numbered lines.
File.WriteAllLines("planets.txt", planets)
WriteAllLines takes any sequence of strings, so an F# list,
an array or a seq expression all work.
λ dotnet fsi lines.fsx 4 lines 1. Mercury 2. Venus 3. Earth 4. Mars
Appending
The Write methods replace the content of a file. To add to
the end of an existing file we use File.AppendAllText or
File.AppendAllLines; they create the file if it does not
exist yet.
open System.IO
let logFile = "visits.log"
let count =
if File.Exists logFile then File.ReadAllLines(logFile).Length else 0
let entry = sprintf "visit %d" (count + 1)
File.AppendAllLines(logFile, [ entry ])
printfn "added '%s'" entry
Each run of the script appends one line to a log file.
let count =
if File.Exists logFile then File.ReadAllLines(logFile).Length else 0
File.Exists tells whether the file is there. On the first
run it is not, and the count starts at zero. We run the script three times
and print the file.
λ dotnet fsi append.fsx added 'visit 1' λ dotnet fsi append.fsx added 'visit 2' λ dotnet fsi append.fsx added 'visit 3' λ cat visits.log visit 1 visit 2 visit 3
Missing files
Reading a file that does not exist throws a
FileNotFoundException. Checking with File.Exists
first is not enough in general, because another program may delete the file
between the check and the read. The safe way is to try the read and handle
the error, as shown in F# exceptions.
open System
open System.IO
let tryReadLines (path: string) =
try
Ok (File.ReadAllLines path)
with
| :? FileNotFoundException -> Error $"{path}: no such file"
| :? DirectoryNotFoundException -> Error $"{path}: no such directory"
| :? UnauthorizedAccessException -> Error $"{path}: access denied"
for path in [ "planets.txt"; "moons.txt"; "data/moons.txt" ] do
match tryReadLines path with
| Ok lines -> printfn "%s: %d lines" path lines.Length
| Error msg -> printfn "%s" msg
The function returns a Result instead of throwing.
| :? DirectoryNotFoundException -> Error $"{path}: no such directory"
A missing directory in the path gives a different exception than a missing
file. Both derive from IOException, which could be caught
instead when the reason does not matter. planets.txt exists
from the previous section.
λ dotnet fsi missing.fsx planets.txt: 4 lines moons.txt: no such file data/moons.txt: no such directory
Reading lazily
ReadAllLines loads the whole file into memory.
File.ReadLines returns a lazy
sequence instead: it reads a line only
when the next element is needed, so it handles files of any size and can
stop early.
Bratislava 475000 Kosice 229000 Presov 83000 Zilina 79000 Nitra 75000 Banska Bystrica 73000 Trnava 63000
The file lists towns with their populations.
open System.IO
let firstSmall =
File.ReadLines "cities.txt"
|> Seq.find (fun line -> int (line.Substring(line.LastIndexOf ' ' + 1)) < 80000)
printfn "first town under 80000: %s" firstSmall
let total =
File.ReadLines "cities.txt"
|> Seq.sumBy (fun line -> int (line.Substring(line.LastIndexOf ' ' + 1)))
printfn "total population: %d" total
We look for the first town with fewer than 80,000 people and add up all populations.
|> Seq.find (fun line -> int (line.Substring(line.LastIndexOf ' ' + 1)) < 80000)
The number starts after the last space, because a town name may contain
spaces. Seq.find stops at the fourth line; the rest of the
file is never read. The file is closed when the sequence finishes or stops.
The second pipeline opens the file again and reads it to the end.
λ dotnet fsi lazy.fsx first town under 80000: Zilina 79000 total population: 1077000
Writing with a stream
A StreamWriter keeps a file open and writes text in pieces.
The fprintfn function works like printfn but
writes to a writer, with the same format specifiers.
open System.IO
let squares () =
use writer = new StreamWriter("squares.txt")
fprintfn writer "%4s %6s" "n" "n*n"
for n in 1 .. 5 do
fprintfn writer "%4d %6d" n (n * n)
fprintf writer "%s" "end\n"
squares ()
printf "%s" (File.ReadAllText "squares.txt")
The script writes a small table of squares.
use writer = new StreamWriter("squares.txt")
use closes the writer when the function ends. A writer
buffers its output, so the text may not reach the file before it is
closed; reading the file inside squares could show an empty
file. The new keyword is recommended for objects that must be
disposed, and the compiler warns when it is missing.
λ dotnet fsi writer.fsx n n*n 1 1 2 4 3 9 4 16 5 25 end
Reading with a stream
A StreamReader reads a file one line at a time with
ReadLine, which returns null at the end of the
file, the same as Console.ReadLine at the end of input.
open System.IO
let longestLine (path: string) =
use reader = new StreamReader(path)
let mutable longest = ""
let mutable number = 0
let mutable line = reader.ReadLine()
while not (isNull line) do
number <- number + 1
if line.Length > longest.Length then
longest <- line
line <- reader.ReadLine()
number, longest
let count, longest = longestLine "cities.txt"
printfn "%d lines, longest: %s" count longest
The function finds the longest line of a file.
let mutable line = reader.ReadLine() while not (isNull line) do
This style uses constant memory however large the file is. With
File.ReadLines the same function would be a one-liner, but a
reader is useful when the format is not line-based, for example with
reader.Read(), which reads one character.
λ dotnet fsi reader.fsx 7 lines, longest: Banska Bystrica 73000
Encodings and bytes
A file stores bytes, and an encoding decides how characters
become bytes. .NET writes UTF-8 by default. The Encoding
class from System.Text selects another encoding, and
File.ReadAllBytes shows what is really in the file.
open System.IO
open System.Text
let word = "čaj"
File.WriteAllText("utf8.txt", word)
File.WriteAllText("utf16.txt", word, Encoding.Unicode)
File.WriteAllText("latin1.txt", word, Encoding.Latin1)
for name in [ "utf8.txt"; "utf16.txt"; "latin1.txt" ] do
let bytes = File.ReadAllBytes name
let hex = bytes |> Array.map (sprintf "%02X") |> String.concat " "
printfn "%-10s %d bytes: %s" name bytes.Length hex
printfn "%s" (File.ReadAllText "utf16.txt")
printfn "%s" (File.ReadAllText "latin1.txt")
The Slovak word for tea is written in three encodings.
File.WriteAllText("utf16.txt", word, Encoding.Unicode)
UTF-8 needs two bytes for č and one for each ASCII letter.
Encoding.Unicode is UTF-16, which starts the file with the
byte order mark FF FE and uses two bytes per character.
Latin-1 has no č, so .NET writes the closest letter it has,
a plain c, and the information is lost without an error.
printfn "%s" (File.ReadAllText "utf16.txt")
ReadAllText recognizes the byte order mark and decodes the
UTF-16 file correctly. Files without a mark are read as UTF-8 unless an
encoding is passed.
λ dotnet fsi encoding.fsx utf8.txt 4 bytes: C4 8D 61 6A utf16.txt 8 bytes: FF FE 0D 01 61 00 6A 00 latin1.txt 3 bytes: 63 61 6A čaj caj
Reading a CSV file
CSV files store a table with one record per line and values separated by
commas. A simple CSV file without quoted values can be split with
String.Split and turned into
records.
date,customer,item,quantity,price 2026-11-02,Novak,keyboard,2,39.90 2026-11-02,Horvath,monitor,1,189.00 2026-11-05,Novak,mouse,3,14.50 2026-11-09,Kovacova,keyboard,1,39.90 2026-11-12,Horvath,cable,4,6.25
This is the input file. The first line is a header with the column names.
open System
open System.IO
open System.Globalization
type Order =
{ Date: DateOnly; Customer: string; Item: string; Quantity: int; Price: decimal }
let inv = CultureInfo.InvariantCulture
let parseOrder (line: string) =
let f = line.Split ','
{ Date = DateOnly.ParseExact(f[0], "yyyy-MM-dd", inv)
Customer = f[1]
Item = f[2]
Quantity = int f[3]
Price = Decimal.Parse(f[4], inv) }
let orders =
File.ReadLines "orders.csv"
|> Seq.skip 1
|> Seq.map parseOrder
|> Seq.toList
for o in orders do
let date = o.Date.ToString("yyyy-MM-dd", inv)
printfn "%s %-9s %-9s %d x %6.2M" date o.Customer o.Item o.Quantity o.Price
Each line after the header becomes an Order record.
|> Seq.skip 1
Seq.skip 1 drops the header line. Dates and prices are parsed
with the invariant culture, so the program reads the file the same way on
every computer. Dates are described in
F# dates and times. A file whose values
may contain commas inside quotes needs a real CSV parser, such as the one in
the FSharp.Data library.
λ dotnet fsi orders.fsx 2026-11-02 Novak keyboard 2 x 39.90 2026-11-02 Horvath monitor 1 x 189.00 2026-11-05 Novak mouse 3 x 14.50 2026-11-09 Kovacova keyboard 1 x 39.90 2026-11-12 Horvath cable 4 x 6.25
Writing a report
The last program reads the orders, adds up the sales per customer and writes the result to a new CSV file.
open System
open System.IO
open System.Globalization
let inv = CultureInfo.InvariantCulture
let parse (line: string) =
let f = line.Split ','
f[1], decimal (int f[3]) * Decimal.Parse(f[4], inv)
let totals =
File.ReadLines "orders.csv"
|> Seq.skip 1
|> Seq.map parse
|> Seq.groupBy fst
|> Seq.map (fun (customer, sales) -> customer, Seq.sumBy snd sales)
|> Seq.sortByDescending snd
|> Seq.toList
let lines =
[ yield "customer,total"
for customer, total in totals do
yield customer + "," + total.ToString("F2", inv) ]
File.WriteAllLines("totals.csv", lines)
printfn "wrote %d customers to totals.csv" totals.Length
The program groups the orders by customer and writes one line per customer.
f[1], decimal (int f[3]) * Decimal.Parse(f[4], inv)
Only the customer and the value of the order are needed, so the parser
returns a tuple. The quantity is converted to decimal before
the multiplication, because the price is a decimal.
yield customer + "," + total.ToString("F2", inv)
The totals are formatted with the invariant culture as well. In a German or Slovak culture a decimal comma would split each value into two CSV columns.
λ dotnet fsi report.fsx wrote 3 customers to totals.csv λ cat totals.csv customer,total Horvath,214.00 Novak,123.30 Kovacova,39.90
Source
.NET documentation: File and stream I/O
In this article we have written and read whole files and lines, appended
to a file, handled missing files, read files lazily with
File.ReadLines, used StreamWriter with
fprintfn and StreamReader, compared encodings and
read and written CSV files. Working with directories and paths is covered
in F# directories and paths, and
use and exceptions in
F# exceptions.
Author
List all F# tutorials.