Loading...
# Reading a file line by line, using loop's :iterate verb, and adding the line lengths
(with [fl (file/open "filepath")]
(var sm 0)
(loop [line :iterate (file/read fl :line)]
(+= sm (length line)))
sm)
MikeBellerPlayground### read a file line by line ###
(let [f (file/open "filename.txt")] # bind an open file handle to "f"
(while true # loop until "break" is called
(let [l (file/read f :line)] # bind a line of the file to "l"
(if l
(print l) # if l is truthy print l
(break)))) # if l is not break from loop
(file/close f)) # close the file handle
# same as above but using "with"
# this means there's no need to
# call file/close, also replace
# let with var
(with [f (file/open "filename.txt")]
(while true
(var l (file/read f :line))
(if l
(print l)
(break))))
yvanPlayground(defn read-from-file [file-path]
(let [f (file/open file-path :r)
content (file/read f :all)]
(file/close f)
content))
### USAGE
(read-from-file "/path/to/file-read-example.janet")
# => @"(defn read-from-file [file-path]\n (let [f (file/open file-path :r)\n content (file/read f :all)]\n (file/close f)\n content))\n"
harryvederciPlayground#!/usr/bin/env janet
# echo stdin to stdout.
(file/write stdout (file/read stdin :all))
cellularmitosisPlayground