Learn Python Β· 7/15

File Handling: Reading and Writing Data

8 min read

Course: Python 🐍

Topic: File Handling: Reading and Writing Data πŸ“

Hey there! Welcome to the guide on handling files in Python. Sooner or later in your programming journey, you'll need your program to remember things even after it has stopped running. You might need to save user data, read a configuration file, or process a large dataset. This is where file handling comes in. It's the skill of teaching your Python script to communicate with files on your computer.

Let's get started and learn how to make your programs read and write data, giving them a memory that lasts!


1. Opening, Reading, and Closing Files πŸ“–

The Problem: Imagine your Python program has a great joke, but every time you run the program, you have to type the joke all over again. Wouldn't it be easier to store the joke in a file and have your program read it from there? To do that, we first need to learn how to open, read, and then properly close a file.

Opening a File:

To open a file, we use the built-in open() function. It takes the file path as the first argument and the mode in which we want to open the file as the second argument. The mode is a string that tells Python what we plan to do with the file.

The most common mode for reading is 'r'.

python
# Let's say we have a file named 'joke.txt' in the same directory.
# The content of 'joke.txt' is:
# Why don't scientists trust atoms?
# Because they make up everything!

file_object = open('joke.txt', 'r')

Think of this file_object as a remote control to your file. It's not the file itself, but it's the connection your script uses to interact with the file's content.

Reading from a File:

Once the file is open, you can read its content in a few ways:

  • .read(): This method reads the entire content of the file and returns it as a single string. Be careful with this one on very large files, as it can consume a lot of memory!

    python
    content = file_object.read()
    print(content)
    # Output:
    # Why don't scientists trust atoms?
    # Because they make up everything!
  • .readline(): This method reads a single line from the file. If you call it again, it will read the next line.

    python
    line1 = file_object.readline()
    print(line1)
    # Output: Why don't scientists trust atoms?
    
    line2 = file_object.readline()
    print(line2)
    # Output: Because they make up everything!
  • .readlines(): This method reads all the lines in the file and returns them as a list of strings.

    python
    lines = file_object.readlines()
    print(lines)
    # Output: ['Why don\'t scientists trust atoms?\n', 'Because they make up everything!']

Closing a File:

This is a crucial step. After you're done with a file, you must close it using the .close() method.

The Problem: Why is closing so important? Operating systems have a limit on the number of files a program can have open simultaneously. If you forget to close files, you can hit this limit, and your program will crash. It's like leaving all the doors in your house wide open; it's not secure and can cause problems.

python
file_object = open('joke.txt', 'r')
content = file_object.read()
file_object.close() # Don't forget this!

print(content)

🧠 Fun Fact: The concept of a hierarchical file system (folders inside folders) that we use every day was a major innovation. One of the earliest popular implementations was in the Multics operating system in the 1960s, a predecessor to Unix!


2. Writing and Appending to Text Files ✍️

The Problem: Reading files is great, but what if you want your program to save its own data? Maybe you're creating a simple to-do list application and need to save the tasks to a file. This is where writing and appending come into play.

Modes for Writing and Appending:

  • 'w' (Write mode): This mode is used to write to a file. If the file already exists, be careful, its entire content will be erased and replaced with what you write. If the file doesn't exist, Python will create it for you.
  • 'a' (Append mode): This mode is for adding new content to the end of an existing file. If the file doesn't exist, it will be created.

Writing to a File:

Let's create a new file and write a to-do list to it.

python
# Using 'w' mode
todo_file = open('todos.txt', 'w')
todo_file.write("1. Learn Python file handling.\n")
todo_file.write("2. Practice with examples.\n")
todo_file.close()

If you check your directory, you'll now find a todos.txt file with those two lines.

Appending to a File:

Now, what if we want to add another item to our list without deleting the existing ones? We use append mode.

python
# Using 'a' mode
todo_file = open('todos.txt', 'a')
todo_file.write("3. Build something awesome!\n")
todo_file.close()

Now, your todos.txt file will look like this:

markdown
1. Learn Python file handling.
2. Practice with examples.
3. Build something awesome!

3. Using the 'with' Statement for Context Management 🀝

The Problem: We've established that forgetting to close() a file is a bad idea. But humans are forgetful! Also, if an error happens in your code between opening and closing a file, the .close() line might never be reached. How can we make sure our files are always closed, no matter what?

The Solution: The with Statement

The with statement is the modern, recommended, and "Pythonic" way to handle files. It automatically manages the file's lifecycle, meaning it ensures the file is closed for you, even if errors occur.

Here's how it looks:

python
with open('todos.txt', 'r') as todo_file:
    content = todo_file.read()
    # No need to call todo_file.close()!
    # Python does it for you once you exit this block.

print(content)

How it Works (Under the Hood): The with statement creates a "context" for your file operations. When the block of code inside the with statement is finished (or if an error causes it to exit), Python automatically calls a special method that closes the file. This makes your code cleaner and safer.

Industry Standard: In professional Python code, you will almost always see file handling done with the with statement. It's a best practice you should adopt right away.


4. Working with CSV and JSON Files πŸ“Š

Plain text files are simple, but a lot of the data in the world is structured. Two of the most common formats for structured data are CSV and JSON. Python has built-in modules to make working with these a breeze.

CSV (Comma-Separated Values)

The Problem: How do you handle data that's organized in a table, like a spreadsheet? Manually splitting lines by commas can be tricky, especially if some of your data also contains commas.

CSV files are perfect for tabular data. Each line is a row, and commas separate the columns. Python's csv module is here to help.

Reading a CSV File:

Let's imagine we have a data.csv file:

csv
name,department,skill
Alice,Engineering,Python
Bob,Marketing,SEO
Charlie,Engineering,Java

We can read it easily with the csv module:

python
import csv

with open('data.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)

    # The reader is an iterator, so we can loop over it.
    for row in csv_reader:
        print(row)

# Output:
# ['name', 'department', 'skill']
# ['Alice', 'Engineering', 'Python']
# ['Bob', 'Marketing', 'SEO']
# ['Charlie', 'Engineering', 'Java']

JSON (JavaScript Object Notation)

The Problem: How do you represent more complex data, like nested lists and dictionaries? This is extremely common when you're getting data from a web API.

JSON is the standard for data exchange on the web. It looks very similar to Python dictionaries. The json module helps you convert between Python objects and JSON strings.

Reading a JSON File:

Let's say we have a user.json file:

json
{
  "username": "coder_dev",
  "id": 12345,
  "is_active": true,
  "roles": ["admin", "editor"]
}

We can load this directly into a Python dictionary:

python
import json

with open('user.json', 'r') as json_file:
    user_data = json.load(json_file)

print(user_data)
print(f"Username: {user_data['username']}")
print(f"Roles: {user_data['roles']}")

# Output:
# {'username': 'coder_dev', 'id': 12345, 'is_active': True, 'roles': ['admin', 'editor']}
# Username: coder_dev
# Roles: ['admin', 'editor']

Notice how true in JSON was automatically converted to True in Python!

Writing a JSON File:

We can also do the reverse: convert a Python dictionary into a JSON file.

python
import json

new_user = {
    'name': 'Dana',
    'id': 67890,
    'courses': [
        {'title': 'Python Basics', 'completed': True},
        {'title': 'Advanced Python', 'completed': False}
    ]
}

with open('new_user.json', 'w') as json_file:
    json.dump(new_user, json_file, indent=4)

The indent=4 argument is a nice touch. It makes the JSON file human-readable by formatting it with an indent of 4 spaces. Your new_user.json will look beautifully structured.

πŸ˜‚ A Programmer's Nightmare: Imagine trying to parse a complex JSON file with thousands of nested objects using only string manipulation methods like .split() and .find(). You'd be lost in a forest of curly braces and quotation marks forever! Always use the json module; it's your trusted guide.


Further Reading & References πŸ“š

For when you're ready to dive deeper, here are the official documentation pages. They are the ultimate source of truth!

  1. Reading and Writing Files in Python: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
  2. csv β€” CSV File Reading and Writing: https://docs.python.org/3/library/csv.html
  3. json β€” JSON encoder and decoder: https://docs.python.org/3/library/json.html

Challenge

Challenge: JSON Data Transformation

You are provided with a multi-line string variable, user_data_json, which simulates the content read from a JSON file. This string contains a list of user profiles.

Your task is to write a Python script that performs the following data manipulation steps:

  1. Import the necessary built-in module for handling JSON data.
  2. Parse the user_data_json string into a native Python data structure (a list of dictionaries).
  3. Locate the dictionary corresponding to the user with an id of 102.
  4. Update the email field for this specific user to [email protected].
  5. Add a new key-value pair to this user's dictionary: "status": "active".
  6. Convert the modified Python data structure back into a JSON-formatted string.
  7. Ensure the resulting JSON string is "pretty-printed" with an indentation level of 4 spaces for readability.
  8. Assign the final, formatted JSON string to a variable named updated_user_data.

Expected result

The final script should correctly modify the user data and store the result in the updated_user_data variable. This variable should hold a single, multi-line string formatted as a JSON array.

The JSON structure should be identical to the original, with the following exceptions for the object where "id": 102:

  • The email value must be changed to "[email protected]".
  • A new field, "status": "active", must be present.
  • The entire string must be formatted with an indent of 4 spaces.

Here is the exact expected string content:

json
[
    {
        "id": 101,
        "name": "John Smith",
        "email": "[email protected]"
    },
    {
        "id": 102,
        "name": "Jane Doe",
        "email": "[email protected]",
        "status": "active"
    },
    {
        "id": 103,
        "name": "Peter Jones",
        "email": "[email protected]"
    }
]
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.