Working with Text Files - Read and Write Files in Python
10th October 2025 By Gururaj
blog

Saving and retrieving data is a crucial skill in programming, as it allows your programs to store information permanently, even after they stop running. Today, we’ll dive into the basics of working with text files on your computer, covering how to open, read, write, and manage them effectively. This is essential for tasks like saving user preferences, logging program activity, or handling data for analysis. Let’s explore this topic in detail, breaking it down into clear, manageable concepts.

Why Work with Text Files?

Text files are a simple, universal way to store data. They’re human-readable, lightweight, and supported by virtually every programming language. Whether you’re saving a user’s high score in a game, storing a list of tasks in a to-do app, or logging errors for debugging, text files provide a reliable way to make data persistent. Unlike variables that disappear when a program ends, data written to a file remains available for future use.

Opening a Text File

To work with a text file, you first need to open it. Most programming languages provide built-in functions or libraries to do this. When opening a file, you typically specify:

  • The file path: Where the file is located (e.g., "data.txt" or "C:/Users/You/Documents/data.txt").
  • The mode: What you want to do with the file, such as:
    • Read ('r'): Access the file’s contents without modifying it.
    • Write ('w'): Create a new file or overwrite an existing one.
    • Append ('a'): Add data to the end of an existing file.
    • Read and Write ('r+'): Both read and modify the file.

For example, in Python, you might open a file like this:

python
 
file = open("data.txt", "r")  # Opens data.txt for reading
 
 

It’s important to close the file when you’re done to free up system resources. Many languages offer a "context manager" (like Python’s with statement) to handle this automatically:

python
 
with open("data.txt", "r") as file:
    # Work with the file
    # File is automatically closed when done
 
 

Reading from a Text File

Once a file is open in read mode, you can retrieve its contents. Common methods include:

  • Reading the entire file: Loads all content into memory as a single string.
  • Reading line by line: Useful for large files, as it processes one line at a time.
  • Reading all lines into a list: Each line becomes an element in a list.

For example, in Python:

python
 
with open("data.txt", "r") as file:
    content = file.read()  # Reads entire file as a string
    print(content)
 
 

Or, to read line by line:

python
 
with open("data.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip() removes extra newlines
 
 

Writing to a Text File

Writing to a file lets you save data permanently. In write mode ('w'), you can create a new file or overwrite an existing one. In append mode ('a'), you add data to the end without erasing existing content.

Example in Python:

python
 
with open("data.txt", "w") as file:
    file.write("Hello, this is a new file!\n")
    file.write("Second line of text.")
 
 

To append instead:

python
 
with open("data.txt", "a") as file:
    file.write("\nAdding a new line to the file.")
 
 

Practical Uses of Text Files

  1. Saving User Preferences: Store settings like a user’s name, theme choice, or game progress in a file.
    • Example: Save a user’s name to "settings.txt" and load it when the program starts.
  2. Logging Activity: Record events, errors, or user actions for debugging or auditing.
    • Example: Append a timestamp and error message to "log.txt" when an error occurs.
  3. Data Storage: Store structured data (e.g., a list of tasks or scores) for later use.
    • Example: Save a list of high scores to "scores.txt" and read them to display a leaderboard.

Best Practices

  • Handle Errors: Files might not exist, be inaccessible, or cause errors. Use try-except blocks to manage issues:
    python
     
    try:
        with open("data.txt", "r") as file:
            content = file.read()
    except FileNotFoundError:
        print("File not found! Creating a new one.")
        with open("data.txt", "w") as file:
            file.write("Default content")
     
     
  • Use Meaningful File Names and Paths: Ensure files are saved in an appropriate location (e.g., a dedicated data folder).
  • Avoid Hardcoding Paths: Use relative paths or configuration settings to make your program portable.
  • Close Files Properly: Always use context managers or explicitly close files to prevent resource leaks.
  • Consider File Formats: For simple data, plain text is fine. For complex data, consider formats like CSV, JSON, or databases for better structure.

Beyond Text Files

While text files are great for simple tasks, they have limitations for large or complex data. For advanced use cases, you might explore:

  • CSV Files: For tabular data (e.g., spreadsheets).
  • JSON Files: For structured, hierarchical data.
  • Databases: For large-scale or relational data storage.

Example: A Simple Task List App

Let’s tie it together with a small example in Python that manages a task list stored in a text file:

python
 
def add_task(task):
    with open("tasks.txt", "a") as file:
        file.write(task + "\n")

def view_tasks():
    try:
        with open("tasks.txt", "r") as file:
            tasks = file.readlines()
            if tasks:
                for i, task in enumerate(tasks, 1):
                    print(f"{i}. {task.strip()}")
            else:
                print("No tasks found!")
    except FileNotFoundError:
        print("No tasks file found. Start adding tasks!")

# Add some tasks
add_task("Buy groceries")
add_task("Finish homework")

# View the tasks
view_tasks()
 
 

This program saves tasks to "tasks.txt" and displays them when requested. The data persists between runs, making it a simple but functional app.

Conclusion

 

Working with text files is a foundational skill that opens up countless possibilities for making your programs more useful and persistent. By mastering how to open, read, and write files, you can save user data, log activity, and manage information effectively. Start experimenting with small projects, like saving a high score or creating a simple log file, to get comfortable with these concepts. As you grow, you’ll find text files are just the beginning of data persistence in programming!