View Category

Read the contents of a file into a string

python
contents = open('myFile.txt', 'rt').read()
clojure
(slurp "/tmp/foobar")
erlang
Text = readfile("Solution607.erl"),
Text = readfile("Solution608.erl"),

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())
clojure
(defn read-line-by-line [fn]
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))
erlang
Reader = fun (IODevice) -> io:get_line(IODevice, "") end,
Worker = fun (Line, N) -> io:format("~B> ~s", [N, Line]), N + 1 end,

while_not_eof("Solution609.erl", Reader, Worker, 1).
Reader = fun (Filename) -> {ok, Contents} = file:read_file(Filename), Contents end,
Transformer = fun (Line, N) -> string:concat(string:concat(integer_to_list(N), "> "), Line) end,
Printer = fun (Line) -> io:format("~s~n", [Line]) end,

Lines = string:tokens(binary_to_list(Reader("Solution610.erl")), "\n"),
NewLines = lists:zipwith(Transformer, Lines, lists:seq(1, length(Lines))),
lists:foreach(Printer, NewLines).

Write a string to a file

python
open('test.txt', 'wt').write('Hello World!')
clojure
(with-out-writer "output.txt" (println "Hello file!"))
erlang
Line = "This line overwites file contents!\n",
{ok, IODevice} = file:open("test.txt", [write]), file:write(IODevice, Line), file:close(IODevice).

Append to a file

python
open('test.txt', 'at').write('Hello World!\n')
clojure
(with-out-append-writer "output.txt" (println "This is appended to the file"))
erlang
Line = "This line appended to file!\n",
{ok, IODevice} = file:open("test.txt", [append]), file:write(IODevice, Line), file:close(IODevice).

Process each file in a directory

python
import os
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (.listFiles (File. ".")))
erlang
% File basenames only - many tasks require absolute paths to work
lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, file:list_dir(Directory)).
% Absolute paths provided - will accomodate most tasks
lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, list_dir_path(Directory)).

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)
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (file-seq (File. ".")))
erlang
filelib:fold_files(Directory, ".*", true, fun (FileOrDirPath, Acc) -> Worker(FileOrDirPath), Acc end, []).
process_dir(Directory, Worker).