Append text to a file in Python

Open a file in append mode, write complete lines, read appended content, and distinguish flushing buffers from syncing data to disk.

Best practices
Append text to a file in Python illustration

Open a text file with mode 'a' to add content at the end without truncating existing data. A with statement closes the file when the block ends, including when an exception is raised.

with open('app.log', 'a', encoding='utf-8') as file:
    file.write('A new log entry\n')

Append mode creates the file if it does not exist, but it does not create missing parent directories. write() does not add a newline for you.

Choose the right mode

Mode Behavior
'a' Append text; create the file if missing
'a+' Append text and allow reading
'w' Write text, truncating an existing file
'x' Create a new file; fail if it already exists

Use binary modes such as 'ab' when writing bytes, and omit the text encoding argument.

Append several lines

lines = ['First line', 'Second line']
with open('data.txt', 'a', encoding='utf-8') as file:
    file.writelines(line + '\n' for line in lines)

writelines() does not insert separators. Supplying each newline explicitly keeps the resulting file readable.

Flush buffers when timing matters

import os

with open('events.log', 'a', encoding='utf-8') as file:
    file.write('Critical event\n')
    file.flush()             # Move Python-buffered data to the OS
    os.fsync(file.fileno())   # Request filesystem synchronization

Closing the file also flushes Python’s buffers, but flush() alone is not a guarantee that data has reached persistent storage. Synchronization has a cost; choose it according to durability requirements.

FAQ

Why can I not read the content I just appended?

Mode 'a' is write-only. With 'a+', flush pending writes and call file.seek(0) before reading from the beginning. Reading at the end of the file returns an empty string even when the data was written successfully.

Is appending from several processes safe?

Do not assume one Python text write is an atomic logical record across every filesystem. Buffering, write sizes, and network filesystems affect behavior. Use a coordinated writer, a logging queue, or appropriate interprocess locking when records must not interleave.

See Python built-in functions, Python operating-system interfaces.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting