Explain Codes LogoExplain Codes Logo

How do I append to a file?

python
file-handling
file-modes
file-io
Alex KataevbyAlex Kataev·Sep 17, 2024
TLDR

To append to a file in Python, use the open() function with the 'a' mode and call the write() function:

with open('file.txt', 'a') as f: f.write("More text\n") # Adds text without a time machine (preserving past data)

The a flag ensures new content is tacked onto the end, without disturbing existing data.

A guide to file modes

Understanding and choosing the appropriate file mode is essential:

  • 'a' : Opens the file for appending. Current file content is preserved. Like using a photocopier instead of a shredder.
  • 'a+' : Opens for appending and reading. You can seek other parts of the file. It's like having cake and eating it too.
  • 'w' : Opens for writing, however file gets truncated first. It's all about right here, right now.
  • 'w+', 'r+', 'a+' : Opens for updating (both reading and writing), the Swiss army knife of file handling.

For dealing with binary data, add b to the mode (like 'ab', 'ab+').

Preserving atomicity

Appending is generally atomic, ensuring that your file does not end up like a Frankenstein monster. This means the operation is immune to interruptions, and can append to the same file without risking data corruption.

Hold with your files

Using the with statement ensures the file is automatically closed once we're done with it - no need to remind Python about it.

with open('file.txt', 'a') as f: f.write("I auto-close, no babysitting needed!\n")

Append file cursor location with 'a+'

In 'a+' mode, no matter what part of the file you're spying on (with seek()), rest assured, your writes will still land at the end. Perfect for those secret diary entries.

Appending ≠ Overwriting

Be careful! 'w' mode in Python's open() is not a shy and retiring typewriter. It overwrites all excitedly, so stick to 'a' mode for careful, respectful appending.

Reading before appending

In some cases, we want to peep at the last entry before adding new stuff. 'a+' mode is your friend here:

with open('log.txt', 'a+') as log: log.seek(0) # Scrolls to the start of file faster than you can say 'Python' last_entry = log.readlines()[-1] log.write("More gossip!\n") # Adds entry even though we were reading above

Binary and text files divergence

For binary files, remember to use 'b' in the mode to ensure that the data is handled properly as binary and not converted into a text-soup.

with open('image.png', 'ab') as f: f.write(b'\x00\x00') # Appends two null bytes, not a love letter

Advanced use cases

Appending in a loop

You can append iteratively like an eager beaver with a diary:

data = ["Thought 1", "Thought 2", "Thought 3"] with open('diary.txt', 'a') as f: for thought in data: f.write(f"{thought}\n")

Thread-safe append

To deal with simultaneous access, use a locking mechanism like threading.Lock to prevent a car crash in a multi-threaded environment:

import threading lock = threading.Lock() with lock: with open('file.txt', 'a') as f: f.write("Traffic controlled append. 🚦\n")

The omnipotent file cursor

In 'a+' mode, the file cursor is like a rebellious teenager. It start at the end for writing, but can be shoved around for reading:

with open('file.txt', 'a+') as f: f.seek(0) content = f.read() # I read from wherever f.write("But I write at the end. 🏁\n") # But still stick to my habits