Introduction

File handling is a crucial part of programming, allowing you to interact with files on your computer. Python provides built-in functions for reading and writing files, making it easy to work with various file formats. In this guide, we'll explore how to handle files in Python, understand different file modes, and provide sample code to illustrate file operations.


Reading Files

Python allows you to read the contents of a file using various methods. Let's explore how to read a file with sample code:


1. Reading the Entire File

# Opening and reading an entire file
with open('sample.txt', 'r') as file:
contents = file.read()

2. Reading Line by Line

# Opening and reading a file line by line
with open('sample.txt', 'r') as file:
for line in file:
print(line)

Writing Files

Python also allows you to create and write data to files. Let's explore how to write to a file with sample code:


1. Writing to a New File

# Opening and writing to a new file
with open('output.txt', 'w') as file:
file.write("Hello, Python!")

2. Appending to an Existing File

# Opening and appending to an existing file
with open('output.txt', 'a') as file:
file.write("\nAppended Text")

File Modes

Python supports different file modes that determine how files are opened and processed. Common file modes include 'r' for reading, 'w' for writing, and 'a' for appending. Understanding these modes is essential for safe file handling.


Exception Handling in File Handling

When working with files, it's essential to handle exceptions, such as file not found errors. Python's error handling mechanisms like try and except can be used for robust file handling.


Conclusion

Python file handling is a critical skill for any programmer, enabling you to read and write data to files. Understanding file modes and exception handling is essential for safe and effective file operations. Mastering file handling is fundamental for working with real-world data and applications.