Write Files
In short: Transferring data from a program into a file — either as plain text or as raw data (bytes).
In more detail: For text, many languages offer buffered writing helper classes (see BufferedWriter), which first collect data and then write it to the storage device in a batch, instead of writing physically immediately on every single call — this is significantly faster. It’s important to close the file again after writing (see try-with-resources), so all buffered data is actually saved.
In Depth
with open("output.txt", "w") as f:
for line in data:
f.write(line + "\n")
# when leaving the "with" block: the buffer is flushed AND the file is closedThe reason for buffering lies in speed: a single physical write to a storage device is orders of magnitude slower than a write access to working memory. If every single write() call hit the disk immediately, writing thousands of individual lines would be extremely slow. Instead, a buffer collects the data in working memory and only actually writes it physically in larger blocks — either automatically once the buffer is full, or explicitly when the file is closed (“flush”).
This leads to an important trap: as long as a file hasn’t been cleanly closed (or explicitly “flushed”), written data may exist ONLY in the buffer in working memory — if the program crashes beforehand or is abruptly terminated, this data is lost, even though the code apparently called write() without issue. This is why reliable closing (ideally via try-with-resources or the with statement, which is guaranteed to close even on an exception) isn’t an optional detail, but necessary for correct data persistence.
Another important difference: overwriting vs. appending. By default (mode "w"), an existing file is completely emptied when reopened for writing, before new writing happens. Anyone wanting to append to existing content instead (e.g. for a log file that grows over the program’s runtime) has to explicitly use append mode ("a") — otherwise all previous log entries are lost every time the program restarts.
See also: Files, BufferedWriter, try-with-resources