View Category

Read the contents of a file into a string

python
contents = open('myFile.txt', 'rt').read()
csharp
string contents = System.IO.File.ReadAllText("filename.txt");
fsharp
let file = new FileStream("test.txt", FileMode.Open)
let buffer = new String((new BinaryReader(file)).ReadChars(Convert.ToInt32(file.Length)))
let stream = new StreamReader("test.txt")
let buffer = stream.ReadToEnd()
let buffer = File.ReadAllText("test.txt")
fantom
contents := File(`file.text`).readAllStr

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
python
for no, line in enumerate(open(__file__)):
print "{0}> {1}".format(no+1, line.rstrip())
csharp
int counter = 0;

// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, line);
}
fsharp
let stream = new StreamReader("test.txt")
let mutable i = 1
let mutable line = stream.ReadLine()
while (line <> null) do printfn "%d> %s" i line ; line <- stream.ReadLine() ; i <- i + 1 done
stream.Close()
let proc_a_line (filename : string) proc =
let stream = new StreamReader(filename)
let rec proc_a_line' count line =
match line with
| null -> stream.Close()
| _ -> proc count line ; proc_a_line' (count + 1) (stream.ReadLine())
proc_a_line' 1 (stream.ReadLine())

// ------

let _ = proc_a_line "test.txt" (fun i line -> printfn "%d> %s" i line)
let reader(filename : string) = seq {
use sr = new StreamReader(filename)
while not sr.EndOfStream do
let line = sr.ReadLine()
yield line
done
}

// ------

reader("test.txt") |> Seq.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
File.ReadAllLines("test.txt") |> Array.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
// Unlike ReadAllLines, ReadLines (new in .NET 4) only reads the file
// one line at a time, rather than reading the entire file into an array first.

open System.IO
File.ReadLines("test.txt") |> Seq.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
fantom
File(`input.text`).readAllLines.each |Str s, Int i| { echo("${i+1}> $s") }

Write a string to a file

python
open('test.txt', 'wt').write('Hello World!')
csharp
System.IO.File.WriteAllText("filename.txt", "Some text to write to the file");
fsharp
let stream = new StreamWriter("test.txt", false)
stream.WriteLine("This line overwrites file contents!")
fantom
File(`out.txt`).out.writeChars("some text").flush

Append to a file

python
open('test.txt', 'at').write('Hello World!\n')
csharp
System.IO.File.AppendAllText("filename.txt", "Some text to append to the file");
fsharp
let stream = new StreamWriter("test.txt", true)
stream.WriteLine("This line appended to file!")
fantom
File(`out.txt`).out(true).writeChars("some text").flush

Process each file in a directory

python
import os
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))
csharp
foreach (string filename in System.IO.Directory.GetFiles(directory)) ProcessFile(filename);
fsharp
let dirname = "c:\\"

let processFile filename = printfn "%s" filename
for filename in Directory.GetFiles(dirname) do processFile filename done
let dirname = "c:\\"

Directory.GetFiles(dirname) |> Array.iter (fun filename -> printfn "%s" filename)
fantom
File(`./`).list.each { process(it) }

Process each file in a directory recursively

python
import os
results = (process(os.path.join(p, n)) for p,d,l in os.walk(".") for n in l)
fsharp
let processDirectory dirname proc =
let rec processDirectory' dirname' =
Directory.GetFiles(dirname') |> Array.iter proc
Directory.GetDirectories(dirname') |> Array.iter processDirectory'
processDirectory' dirname

// ------

let dirname = "c:\\"

processDirectory dirname (fun filename -> printfn "%s" filename)
fantom
File(`./`).walk { process(it) }