Python

Working with Files

Files are an important concept in programming, as they allow us to store and retrieve data from our computer’s storage. There are many different types of files, such as text files, image files, and audio files, and we can work with these files using Python.

File Handling in Python:

Python provides built-in functions and modules for file handling. Here’s how you can use them:

# Opening a file for reading
file_path = "example.txt"
with open(file_path, "r") as file:
    content = file.read()
    print(content)
Encapsulation in File Handling:

Encapsulation involves bundling file-related operations within a class or functions. Here’s an encapsulated file handling example:

class FileManager:
    def __init__(self, file_path):
        self.file_path = file_path

    def read_content(self):
        with open(self.file_path, "r") as file:
            return file.read()

    def write_content(self, content):
        with open(self.file_path, "w") as file:
            file.write(content)

# Usage
file_manager = FileManager("example.txt")
content = file_manager.read_content()
print(content)

new_content = "This is the new content."
file_manager.write_content(new_content)
File Modes and Operations:

Python supports various file modes and operations. Here’s an example of writing to a file:

with open("output.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.")
Exception Handling:

Proper error handling is essential when working with files. Use try and except blocks:

try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found.")
Using with Statement for Resource Management:

Using the with statement ensures proper resource management:

with open("data.txt", "r") as file:
    content = file.read()
    print(content)
# File is automatically closed when exiting the block
Examples of Encapsulation in File Handling:

Here’s an example of encapsulation for a simple FileReader class:

class FileReader:
    def __init__(self, file_path):
        self.file_path = file_path

    def read_lines(self):
        with open(self.file_path, "r") as file:
            return file.readlines()

# Usage
reader = FileReader("data.txt")
lines = reader.read_lines()
for line in lines:
    print(line.strip())
Benefits of Encapsulation in File Handling:

Encapsulation ensures data integrity, error handling, and resource management. It makes code more organized and reusable.

With just a few different commands, we are able to access, edit and save files on our own OS without even opening them. But this isn’t the end, for example, we could easily take a CSV file full of data, and output a graph using matplotlib with just a few lines of code!