In the realm of programming, file handling is a fundamental operation that allows us to interact with files on our computer. Python, with its simplicity and readability, provides several ways to handle files efficiently. Let's dive into the world of Python file handling with examples to understand how to read, write, append, and manage files.

Python offers two primary file handling modules: open() and pathlib. The open() function is used for simple file handling, while pathlib is an object-oriented approach to file handling, introduced in Python 3.4, that provides a more intuitive and efficient way to work with files.

File Operations using open()
The open() function is used to open a file in Python. It takes two arguments - file path and mode. The mode argument determines the operation to be performed on the file. It can be 'r' (read), 'w' (write), 'a' (append), 'x' (create), etc.

Let's see an example of reading a file using the 'r' mode:
```python file = open('example.txt', 'r') print(file.read()) file.close() ```
Reading a File

The read() method reads the entire content of the file. If you want to read line by line, use the readline() method or use a for loop with readlines():
```python file = open('example.txt', 'r') for line in file: print(line) file.close() ```
Writing and Appending to a File
To write to a file, use the 'w' mode. If the file exists, its content will be overwritten. To append data without overwriting the existing content, use the 'a' mode:

```python file = open('example.txt', 'w') file.write('Hello, World!\n') file.close() file = open('example.txt', 'a') file.write('Hello, Python!') file.close() ```
File Operations using pathlib
The pathlib module provides an object-oriented interface for file handling. It is more intuitive and often preferred over the open() function. Here's how you can read, write, and append files using pathlib:
Reading a File

You can use the .read_text() method to read the entire content of a file or the .readlines() method to read line by line:
```python from pathlib import Path file = Path('example.txt') print(file.read_text()) for line in file.readlines(): print(line) ```
Writing and Appending to a File




















To write to a file, you can use the .write_text() method. To append data without overwriting the existing content, read the file content first, then append the new data:
```python file = Path('example.txt') file.write_text('Hello, World!\n') content = file.read_text() file.write_text(content + 'Hello, Python!') ```
Python's built-in error handling mechanisms can help manage exceptions during file handling. Always remember to close your files after operations, or use them in a context, like with Python's with statement, to ensure files are closed properly. With this, you're well on your way to mastering file handling in Python.