Python - Reading and Writing Files
os.path
module for file path manipulation.
The os.path
module in Python provides a set of functions for path manipulation, allowing you to work with file and directory paths in a platform-independent way. It includes functions for joining paths, splitting paths, getting the absolute path, checking file existence, and more.
Here's an example program that demonstrates the purpose of the os.path
module for file path manipulation:
import os
# Example file path
file_path = 'example_directory/example_file.txt'
# Get the directory name of the file path
directory_name = os.path.dirname(file_path)
print("Directory Name:", directory_name)
# Get the base name (last component) of the file path
base_name = os.path.basename(file_path)
print("Base Name:", base_name)
# Join two paths to create a new path
new_path = os.path.join('parent_directory', 'child_directory', 'new_file.txt')
print("New Path:", new_path)
# Check if a file exists at the specified path
file_exists = os.path.exists(file_path)
print("File Exists:", file_exists)
In this example, the os.path
module is used to perform various operations on the file path 'example_directory/example_file.txt'
. The functions os.path.dirname()
and os.path.basename()
are used to get the directory name and base name of the file path, respectively. The os.path.join()
function is used to join two paths to create a new path. Finally, the os.path.exists()
function is used to check if a file exists at the specified path.
The output of the program will be:
Directory Name: example_directory Base Name: example_file.txt New Path: parent_directory/child_directory/new_file.txt File Exists: False
To read and write JSON files in Python, you can use the built-in json
module. The json
module provides functions to encode Python objects as JSON strings and decode JSON strings back into Python objects.
Here's an example program that demonstrates reading and writing JSON files:
import json
# Example data for writing to a JSON file
data_to_write = {
'name': 'John Doe',
'age': 30,
'city': 'New York'
}
# Writing data to a JSON file
json_file_path = 'example.json'
with open(json_file_path, 'w') as json_file:
json.dump(data_to_write, json_file, indent=2)
# Reading data from a JSON file
with open(json_file_path, 'r') as json_file:
data_read = json.load(json_file)
print("JSON Content Read:")
print(data_read)
In this example, the program writes data to a JSON file using the json.dump()
function, and then reads the data back from the JSON file using the json.load()
function. The indent=2
parameter is used to format the JSON file with an indentation of 2 spaces for better readability.
The output of the program will be:
JSON Content Read: {'name': 'John Doe', 'age': 30, 'city': 'New York'}
The pickle
module in Python is used for serializing and deserializing Python objects. Serialization is the process of converting a Python object into a byte stream, and deserialization is the process of reconstructing the original object from a byte stream. pickle
is particularly useful for saving and loading complex data structures, including custom objects.
Here's an example program that demonstrates the use of the pickle
module for file serialization:
import pickle
# Example data for serialization
data_to_serialize = {
'name': 'Alice',
'age': 25,
'city': 'Wonderland'
}
# Serialization: Writing data to a pickle file
pickle_file_path = 'example.pickle'
with open(pickle_file_path, 'wb') as pickle_file:
pickle.dump(data_to_serialize, pickle_file)
# Deserialization: Reading data from a pickle file
with open(pickle_file_path, 'rb') as pickle_file:
data_deserialized = pickle.load(pickle_file)
print("Deserialized Data:")
print(data_deserialized)
In this example, the program serializes data to a pickle file using the pickle.dump()
function, and then deserializes the data back from the pickle file using the pickle.load()
function. The file is opened in binary mode ('wb'
and 'rb'
) because pickle deals with binary data.
The output of the program will be:
Deserialized Data: {'name': 'Alice', 'age': 25, 'city': 'Wonderland'}
In file handling, the 'rb'
(read binary) and 'wb'
(write binary) modes in Python are used to indicate that the file being opened or created should be treated as a binary file. These modes are commonly used when working with non-text files, such as images, videos, or serialized data files.
Here's an example program that demonstrates the use of 'rb'
and 'wb'
modes:
# Example data for binary file
binary_data = b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64' # Binary representation of 'Hello World'
# Writing binary data to a file using 'wb' mode
binary_file_path = 'example_binary_file.bin'
with open(binary_file_path, 'wb') as binary_file:
binary_file.write(binary_data)
# Reading binary data from the file using 'rb' mode
with open(binary_file_path, 'rb') as binary_file:
read_binary_data = binary_file.read()
print("Read Binary Data:")
print(read_binary_data)
In this example, the program writes binary data to a file using the 'wb'
mode and then reads the binary data back from the file using the 'rb'
mode. The use of these modes is essential when working with binary data to ensure proper handling and preservation of byte values.
The output of the program will be:
Read Binary Data: b'Hello World'