Python File Handling 

In this tutorial, you will learn about file handling in python

Introduction


File handling is an essential aspect of programming, allowing you to read from and write to files.

Python provides a simple and powerful way to perform file operations, making it easy to work with various types of data.

In this tutorial, we'll explore the fundamentals of Python file handling, including reading from and writing to files, manipulating file pointers, and handling exceptions.

 

Opening and Closing Files


In Python, the open() function is used to open files. It takes two arguments - the file name and the mode. Modes include 'r' for reading, 'w' for writing, and 'a' for appending. After performing file operations, it's crucial to close the file using the close() method.

# Example: Opening and closing a file
file_name = "example.txt"

# Opening a file for reading
file = open(file_name, 'r')
# File operations go here
file.close()

 

Reading from Files


Python provides several methods for reading from files. The read() method reads the entire file, while readline() reads a single line. You can also use readlines() to read all lines into a list.

# Example: Reading from a file
file = open("example.txt", 'r')

# Reading the entire file
content = file.read()
print(content)

# Reading a single line
line = file.readline()
print(line)

# Reading all lines into a list
lines = file.readlines()
print(lines)

file.close()

 

Writing to Files


To write to a file, open it in write or append mode ('w' or 'a'). Use the write() method to add content. Be cautious when using 'w' mode, as it overwrites the entire file.

# Example: Writing to a file
file = open("example.txt", 'w')

# Writing content to the file
file.write("Hello, this is a sample text.")

file.close()

 

Working with Text Files


For text files, it's common to use the with statement, which automatically closes the file after execution. Python 3 also supports specifying the encoding for text files.

# Example: Working with text files
file_path = "example.txt"

# Reading from a text file using 'with'
with open(file_path, 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

# Writing to a text file using 'with'
with open(file_path, 'w', encoding='utf-8') as file:
    file.write("This is a new line.")

 

Working with Binary Files


Binary files, such as images or audio files, require 'rb' (read binary) or 'wb' (write binary) modes. Use the read() and write() methods for binary data.

# Example: Working with binary files
image_path = "image.jpg"

# Reading a binary file
with open(image_path, 'rb') as file:
    binary_data = file.read()
    # Process binary data

# Writing to a binary file
with open("new_image.jpg", 'wb') as file:
    file.write(binary_data)

 

File Positions and Pointers


The tell() method returns the current position of the file cursor, and seek(offset, whence) moves the cursor to a specified position.

# Example: File positions and pointers
file = open("example.txt", 'r')

# Getting the current position
position = file.tell()
print("Current Position:", position)

# Moving the cursor to a specific position
file.seek(10, 0)  # Move 10 characters from the beginning
file.close()

 

Exception Handling in File Operations


When working with files, it's crucial to handle exceptions, such as FileNotFoundError or PermissionError. Use try-except blocks to gracefully manage errors.

# Example: Exception handling in file operations
try:
    file = open("nonexistent.txt", 'r')
    content = file.read()
    file.close()
except FileNotFoundError:
    print("File not found!")
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # Ensure the file is closed even if an exception occurs
    file.close()

 

Summary


File handling is a fundamental skill in Python programming.

With the knowledge gained in this chapter, you can effectively read from and write to files, manipulate file pointers, and handle exceptions that may arise during file operations.

As you continue to develop your Python skills, mastering file handling will become an essential tool in your programming toolkit.
 

© 2022-2023 All rights reserved.