Python File Handling

Python provides several built-in functions for file handling, enabling us to create, read, update, and delete files. Working with files is essential for many programming tasks, such as storing data, logging information, or reading configuration files. Python's file handling capabilities make it simple to work with files. Whether you're reading from, writing to, or appending to a file, Python provides efficient and straightforward methods. Utilizing the with statement ensures proper resource management, making it the recommended approach for file handling.
In this section, we'll explore how to handle files using Python.

Opening a File

The open() function is used to open a file in Python. It takes two arguments: the file name and the mode in which the file should be opened. The most commonly used modes are:

1. Reading from a File


file = open('sample.txt', 'r')
content = file.read()
print(content)
file.close()
            

Output

(Contents of sample.txt will be displayed here)

Writing to a File

To write to a file, we use the 'w' mode. This will overwrite the file if it already exists.

2. Writing to a File


file = open('output.txt', 'w')
file.write('Hello, this is a test file!')
file.close()
            

Output

(The text "Hello, this is a test file!" is written to output.txt)

Appending to a File

Use the 'a' mode to append new content to an existing file.

3. Appending to a File


file = open('output.txt', 'a')
file.write('\nAdding a new line to the file.')
file.close()
            

Output

(The new line is added to output.txt)

Using with Statement

The with statement is used to automatically handle file closing after its suite finishes. This is the preferred way of working with files in Python as it ensures proper resource management.

4. Using the with Statement


with open('sample.txt', 'r') as file:
    content = file.read()
    print(content)
            

Output

(Contents of sample.txt will be displayed here)

Common File Methods