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:
- 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.
with
Statement:- Using
with open(...)
ensures that the file is properly closed after the operation, even if an error occurs during the process.
- Using
- Adding a New Line:
- Include
\n
at the end of your text to add a new line if necessary.
- Include
If example.txt
already has:
Hello, world!
After running the code, the content will be:
Hello, world!
This is the new line of text.
Leave a Reply