Writing Files in Python

Here’s the translation of the Go code example to Python, formatted in Markdown suitable for Hugo:

Writing files in Python follows similar patterns to the ones we saw earlier for reading.

import os

def check(e):
    if e:
        raise e

def main():
    # To start, here's how to dump a string (or just bytes) into a file.
    d1 = b"hello\npython\n"
    with open("/tmp/dat1", "wb") as f:
        f.write(d1)

    # For more granular writes, open a file for writing.
    with open("/tmp/dat2", "w") as f:
        # You can write strings as you'd expect.
        d2 = "some\n"
        n2 = f.write(d2)
        print(f"wrote {n2} bytes")

        # WriteString is not needed in Python as write() can handle strings directly.
        n3 = f.write("writes\n")
        print(f"wrote {n3} bytes")

        # Python doesn't have an explicit Sync method, but you can use flush() to ensure writes are committed.
        f.flush()

        # Python's io module provides buffered writers similar to bufio in Go.
        import io
        buffered_writer = io.BufferedWriter(f)
        n4 = buffered_writer.write("buffered\n".encode())
        print(f"wrote {n4} bytes")

        # Use flush() to ensure all buffered operations have been applied to the underlying writer.
        buffered_writer.flush()

if __name__ == "__main__":
    main()

Try running the file-writing code:

$ python writing_files.py
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files:

$ cat /tmp/dat1
hello
python
$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin and stdout streams.