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).

Frequently asked questions

How do you append to file?
This task is covered in 2 stacks on this page: Bash & Linux, Python. The "Redirect Standard Output" snippet in Bash & Linux uses `command > file`.
Which command does the Bash & Linux example use?
The "Redirect Standard Output" snippet uses `command > file`, from the Redirects & Pipes section of the Bash & Linux cheat sheet.
Which stacks cover "append to file" on this page?
Bash & Linux, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Redirect Standard Output": > 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.