In Python, reading and writing key value pairs to a file is a common task, often done using libraries like JSON.
Reading involves opening a file, loading its contents into a dictionary, and accessing values using keys.
Similarly, writing involves creating a dictionary with key value pairs, converting it to JSON format, and writing it to the file.
Write Key Value Pair to File
First, let me write the Python code that writes key value pairs to a file using the json module.
import json # Define a dictionary with key value pairs data = { "name": "John", "age": 30, "city": "New York" } # Define the file path file_path = "data.json" # Write the dictionary to the file with open(file_path, "w") as file: json.dump(data, file)
I’ll explain the code now.
- Import the json module to work with JSON data.
- Create a dictionary data with key value pairs.
- Define the file path where you want to write the data.
- Open the file in write mode using open() function.
- Use json.dump() function to write the dictionary data to the file in JSON format.
Read Key Value Pair from File
Similar to Write operation, I’ll write now code to read key value pairs from a file.
import json # Define the file path file_path = "data.json" # Read the key value pairs from the file with open(file_path, "r") as file: data = json.load(file) # Access the values using keys name = data["name"] age = data["age"] city = data["city"] print("Name:", name) print("Age:", age) print("City:", city)
Let me explain you the above code.
- Import the json module to work with JSON data.
- Define the file path from which you want to read the data.
- Open the file in read mode using open() function.
- Use json.load() function to load the JSON data from the file into a Python dictionary data.
- Access the values in the dictionary using keys.
- Use the retrieved values as needed.
Writing and reading key value pair in file is one of the most common requirement especially when you want to manage quick & efficient storage in your project.