How do I append to a file in Python?

To append to a file in Python, use the open() function with the 'a' (append) mode. This allows you to add content to the end of an existing file without overwriting it. If the file doesn’t exist, Python will create it.

Basic Example

with open("example.txt", "a") as file:
    file.write("This text will be appended.\n")  # \n ensures a new line

Key Methods

1. Appending a Single Line

with open("data.txt", "a") as f:
    f.write("New data line\n")  # Add a newline character explicitly

2. Appending Multiple Lines

Use writelines() to append a list of strings:

lines = ["First line\n", "Second line\n", "Third line\n"]
with open("log.txt", "a") as f:
    f.writelines(lines)

3. Appending with print()

Use print() to write formatted text:

with open("output.txt", "a") as f:
    print("Appended via print()", file=f)  # Adds a newline by default

Modes Explained

ModeDescription
aAppend text to the file (creates the file if it doesn’t exist).
a+Append and read from the file (cursor at the end for writes, allows reads).
abAppend in binary mode (for non-text files like images).

Best Practices

  1. Use with Statements
    Ensures the file is automatically closed after appending, even if an error occurs.
  2. Handle Newlines
    Add \n to write() calls to avoid appending all text to a single line.
  3. Check File Permissions
    Ensure your script has write access to the file/directory.
  4. Avoid Overwriting
    Unlike 'w' mode, 'a' mode will never delete existing content.

Example: Append User Input

user_input = input("Enter text to append: ")
with open("diary.txt", "a") as f:
    f.write(f"{user_input}\n")  # Append input with a newline

Handling Edge Cases

1. Appending to a Non-Existent File

with open("new_file.txt", "a") as f:
    f.write("This creates the file if it doesn’t exist.\n")

2. Appending Binary Data

with open("image.png", "ab") as f:
    f.write(b"\x89PNG\r\n\x1a\n")  # Append binary data (e.g., a PNG header)

Common Mistakes

  • Forgetting \n:
    Without newline characters, all appended text will be on the same line.
  # Bad: Appends "Line1Line2Line3"
  with open("file.txt", "a") as f:
      f.write("Line1")
      f.write("Line2")
      f.write("Line3")

  # Good: Appends each line separately
  with open("file.txt", "a") as f:
      f.write("Line1\n")
      f.write("Line2\n")
  • Using 'w' Instead of 'a':
    'w' mode overwrites the entire file, while 'a' appends.

Leave a Reply

Your email address will not be published. Required fields are marked *