Append to file

2 snippets across 2 stacks — Bash & Linux, Python

SHBash & Linux

Redirect Standard Output

SH · Redirects & Pipes
syntax
command > file
command >> file
example
echo 'server.port=8080' > app.properties
date >> deployment.log
psql -c 'SELECT * FROM users' > users_export.csv

Note > overwrites the file completely. >> appends to the end. WARNING: Redirecting to a file you are also reading from (e.g., sort file > file) will truncate it to zero bytes. Use a temporary file or sort -o file file instead.

PYPython

Writing Files

PY · File I/O
syntax
with open(path, 'w') as f:
    f.write(text)
example
lines = ["alice,95", "bob,82", "carol,91"]

with open("scores.csv", "w", encoding="utf-8") as f:
    f.write("name,score\n")
    for line in lines:
        f.write(line + "\n")

# Append mode
with open("scores.csv", "a") as f:
    f.write("dave,88\n")

Note 'w' mode truncates the file first. Use 'a' to append. Use 'x' to create exclusively (fails if file exists).