Skip to content

Files

In Python file handling is primarily performed using the built-in open() function. This function returns a file object, also called a handle, as it is used to read or modify the file.

Opening a File

To open a file, you need to specify the file name and the mode in which you want to open the file. The most common modes are:

  • r - Read - Default value. Opens a file for reading, error if the file does not exist.
  • a - Append - Opens a file for appending, creates the file if it does not exist.
  • w - Write - Opens a file for writing, creates the file if it does not exist.
  • x - Create - Creates the specified file, returns an error if the file exists.
Opening a file
f = open("demofile.txt", "r")

The open() function returns a file object that can be used to read, write, or append to the file.

It is not recommended to open files without closing them. When you are done with the file, you should always close it using the close() method.

Closing a file
f = open("demofile.txt", "r")
print(f.read())
f.close()

However, using the with statement is a better way to open files. The advantage of using the with statement is that it will automatically close the file for you. As open is a context manager, it will automatically close the file when the block of code is exited.

Using the with statement
with open("demofile.txt", "r") as f:
    print(f.read())

Working with JSON data

Consider this Python data structure:

data = {
    "network": [
        {
            "device": "switch1",
            "interfaces": [
                {"name": "eth0", "vlan": 10},
                {"name": "eth1", "vlan": 20},
                {"name": "eth2", "vlan": 30},
            ],
        },
        {
            "device": "switch2",
            "interfaces": [
                {"name": "eth0", "vlan": 11},
                {"name": "eth2", "vlan": 22},
                {"name": "eth4", "vlan": 33},
            ],
        },
    ],
    "vlans": [
        {"id": 10, "name": "vlan10", "description": "Production"},
        {"id": 20, "name": "vlan20", "description": "Development"},
        {"id": 30, "name": "vlan30", "description": "Testing"},
        {"id": 11, "name": "vlan11", "description": "Production"},
        {"id": 22, "name": "vlan22", "description": "Development"},
        {"id": 33, "name": "vlan33", "description": "Testing"},
    ],
}

You can convert this Python data structure to a JSON string using the json.dump() function. Then save it to a file for later use or editing. The json.dump() function writes a Python object to a file in JSON format.

Converting Python object to JSON string
import json

with open("data.json", "w") as f:
    json.dump(data, f)

Similarly when you want to read the data back from a JSON file, you can use the json.load() function. This function reads a JSON file and converts it into a Python object.

Converting JSON string to Python object
import json

with open("data.json", "r") as f:
    data = json.load(f)

print(data)

Now you know the basics of file handling in Python. You can read, write, and append to files. You can also work with JSON data by converting Python objects to JSON strings and vice versa.