FileWriter
Standard library class · Made with File.create
A FileWriter is a file that is open for writing. File.write puts a whole
text in a file in one go; a writer lets a program add to the file as it goes, such as a line for
each result of a long calculation, without holding all of it in memory first.
const writer = File.create("squares.txt")for n in 1..4 { writer.write("#{n} squared is #{n * n}\n")}writer.close()
print(File.read("squares.txt"))1 squared is 12 squared is 43 squared is 94 squared is 16File.create makes the file, or empties it if it was already there. Each write adds to the end of
what has been written so far. Nothing is added between writes, so end a line with \n yourself.
A writer only writes. To read a file a piece at a time, use a FileHandle; to add
to a file that already has content, use File.append.
Close the writer when you are done, so everything reaches the file. File.with_writer
does that for you, even if something goes wrong partway:
File.with_writer("squares.txt", { writer => for n in 1..4 { writer.write("#{n * n}\n") }})print(File.read_lines("squares.txt"))["1", "4", "9", "16"]At a glance
Section titled “At a glance”| Writing | |
|---|---|
write(text) |
Add text to the file |
write_bytes(bytes) |
Add raw bytes to the file |
| Finishing | |
|---|---|
close() |
Finish the file and let go of it |
Writing
Section titled “Writing”Adds text to the end of the file, as UTF-8.
Raises a FileError when the text can’t be written, or when the writer has been
closed.
Finishing
Section titled “Finishing”Finishes the file and lets go of it. Closing a writer that is already closed does nothing, so it is safe to close one twice. Writing to a closed writer is an error:
const writer = File.create("note.txt")writer.close()writer.write("too late")note.em:3:1: FileError: cannot write to a closed file writer.write("too late") ^^^^^^^^^^^^^^^^^^^^^^^^Check that the path exists and that this program may access it.