io
lhj
summon ioThe io module gives you lower-level file access. For simple read/write, os.read_file and os.write_file are usually sufficient. Use io when you need line-by-line reading or want to append to a file.
Opening a file
lhj
forge f = io.open("data.txt", "r") ## read mode
forge f = io.open("log.txt", "w") ## write (creates or truncates)
forge f = io.open("log.txt", "a") ## appendModes:
"r"— read"w"— write (overwrites existing content)"a"— append"rb"— read binary"wb"— write binary
Reading
lhj
forge f = io.open("data.txt", "r")
forge all = io.read(f) ## read entire file as string
io.close(f)
## Or line by line
forge f = io.open("data.txt", "r")
forge line = io.readline(f)
march line != "":
echo line
line <- io.readline(f)
io.close(f)
## All lines at once
forge f = io.open("data.txt", "r")
forge lines = io.readlines(f)
io.close(f)
march line in lines:
echo strings.strip(line)Writing
lhj
forge f = io.open("output.txt", "w")
io.write(f, "Hello, file!\n")
io.write(f, "Second line\n")
io.close(f)Using attempt/finally
Always close files, even if reading fails:
lhj
forge f = io.open("data.txt", "r")
attempt:
forge content = io.read(f)
echo content
rescue e:
echo "Read error: {e}"
finally:
io.close(f)Example
lhj
summon io
summon strings
blade word_count(filename):
forge f = io.open(filename, "r")
forge lines = io.readlines(f)
io.close(f)
forge total = 0
march line in lines:
forge words = strings.split(strings.strip(line))
total <- total + len(words)
release total
echo word_count("essay.txt")