Last modified: Feb 14, 2026 By Alexander Williams

Python Save Text File: Write & Append Guide

Working with files is a core skill in programming. In Python, saving data to a text file is simple and powerful.

This guide will teach you the essential methods. You will learn to create, write to, and append to files.

Opening a File for Writing

The first step is to open the file. You use the built-in open() function.

This function needs two main arguments: the file path and the mode. The mode tells Python what you want to do.

To save new content, you use the write mode. This is specified with the 'w' character.


# Open a file for writing. If it doesn't exist, Python creates it.
file = open('my_data.txt', 'w')
    

Be careful. The write mode ('w') will overwrite an existing file. All previous content will be lost.

Writing Text with the write() Method

Once the file is open, you can write strings to it. Use the write() method on the file object.

This method takes a string as an argument. It writes that string directly to the file.

Remember, write() does not automatically add a newline. You must include the newline character '\n' yourself.


# Open the file
file = open('example.txt', 'w')

# Write a single line of text
file.write('Hello, this is line one.\n')

# Write a second line
file.write('This is line two.')

# Always close the file to free resources
file.close()
    

After running this code, a file named example.txt will be created. It will contain the two lines of text.


Hello, this is line one.
This is line two.
    

Appending to an Existing File

What if you want to add text without deleting the old content? You use append mode.

Append mode is specified with the 'a' character when opening the file.

This mode is perfect for logs, data collection, or any time you need to preserve history. For more advanced control over text streams, see our guide on Python TextIOWrapper: Handle Text File Operations Efficiently.


# Open a file for appending
log_file = open('server_log.txt', 'a')

# This text will be added to the end of the file
log_file.write('New log entry at 12:00 PM\n')

log_file.close()
    

The Best Practice: Using 'with' Statement

Manually calling close() is error-prone. If an error occurs before the close, the file might not close properly.

Python's with statement is the solution. It creates a context manager.

The file is automatically closed when the block of code inside the with statement finishes. This is true even if an error happens.


# Using 'with' is the recommended and safest way
with open('notes.txt', 'w') as file:
    file.write('First note.\n')
    file.write('Second note.\n')
# The file is automatically closed here
    

Writing Multiple Lines Efficiently

If you have a list of strings to write, looping with write() works. But there is a better method.

The writelines() method takes a list (or any iterable) of strings. It writes them all to the file.

Just like write(), it does not add newlines. You must ensure they are in your strings.


lines_to_save = [
    'Item 1: Apples\n',
    'Item 2: Oranges\n',
    'Item 3: Bananas\n'
]

with open('shopping_list.txt', 'w') as file:
    file.writelines(lines_to_save)
    

Item 1: Apples
Item 2: Oranges
Item 3: Bananas
    

Handling Different Data Types

The write() method only accepts strings. What if your data is a number or a list?

You must convert non-string data to a string first. Use the str() function for basic conversion.

For complex data like lists or dictionaries, you often use the json module to save structured text.


user_score = 95
message = "Your final score is: " + str(user_score) + "\n"

with open('score.txt', 'w') as f:
    f.write(message)
    

Common Modes for the open() Function

Here is a quick reference for the most common file modes.

  • 'w' : Write. Creates a new file or overwrites an existing one.
  • 'a' : Append. Adds to the end of an existing file or creates a new one.
  • 'r' : Read. Opens a file for reading (default mode).
  • 'x' : Exclusive creation. Only creates a new file; fails if the file exists.
  • 'w+' : Write and read. Overwrites the file, but you can also read from it.
  • 'a+' : Append and read. You can append and read the file.

Understanding these modes gives you full control over your file operations. Once you master saving text, you might explore related tasks like Python Text Extraction from Images Guide to get text into your programs from other sources.

Complete Example: Saving User Input

Let's combine everything into a practical example. This script asks for user input and saves it to a log file.


print("Daily Journal Entry")
print("-------------------")

# Get input from the user
entry_date = input("Enter today's date (YYYY-MM-DD): ")
entry_text = input("Write your journal entry: ")

# Format the data to save
formatted_entry = f"\nDate: {entry_date}\nEntry: {entry_text}\n{'-'*30}\n"

# Open the journal file in append mode to preserve old entries
with open('my_journal.txt', 'a') as journal:
    journal.write(formatted_entry)

print("Your entry has been saved to 'my_journal.txt'.")
    

Daily Journal Entry
-------------------
Enter today's date (YYYY-MM-DD): 2023-10-27
Write your journal entry: Learned how to save files in Python!
Your entry has been saved to 'my_journal.txt'.
    

After running it, the file my_journal.txt will have the new entry appended at the end.

Conclusion

Saving a text file in Python is straightforward. The key steps are using the open() function with the correct mode and the write() or writelines() methods.

Always prefer the with statement for safety. It ensures your files are closed properly.

Remember the difference between write ('w') and append ('a') mode. This prevents accidental data loss.

Start by saving simple strings. Then move on to formatting more complex data. This skill forms the foundation for data persistence in your Python projects.