How to Append Text to a File in Python

5
(1)

To write text to a file in Python and append it to the existing content without overwriting, you can open the file in append mode ('a'). Here’s a step-by-step explanation and an example:

Open the file in append mode (‘a’)

with open(“example.txt”, “a”) as file:
# Write the new text to the file
file.write(“This is the new line of text.\n”)

print(“Text has been added to the file!”)

Key Points:

  1. Append Mode ('a'):
    • If the file does not exist, it will create a new file.
    • If the file exists, it appends the text to the end of the file without removing the existing content.
  2. with Statement:
    • Using with open(...) ensures that the file is properly closed after the operation, even if an error occurs during the process.
  3. Adding a New Line:
    • Include \n at the end of your text to add a new line if necessary.

If example.txt already has:

Hello, world!

After running the code, the content will be:

Hello, world!
This is the new line of text.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Be the first to comment

Leave a Reply

Your email address will not be published.


*