Python Files I/O

Introduction:

In Python, file handling is a simple yet powerful feature that allows users to create, read, write, and manage files. Compared to other programming languages, Python offers a streamlined approach to file handling. The data stored in files is non-volatile, meaning it can be accessed after the program has terminated, making file handling crucial when dealing with large datasets or permanent data storage.

Basic Steps in File Handling:

1. Open the file

2. Perform the operation (read/write)

3. Close the file

Opening a File

To open a file in Python, the open() function is used. It requires two main arguments:

File Name: The name of the file you want to access.

Access Mode: The mode in which you want to open the file (e.g., read, write, append).

Syntax:

file_object = open(<file_name>, <access_mode>)

File Access Modes:

Mode Description
r Opens a file for reading (default). The file pointer is at the beginning.
rb Opens a file for reading in binary format.
r+ Opens a file for reading and writing. The file pointer is at the beginning.
w Opens a file for writing. It overwrites the file if it exists.
wb Opens a file for writing in binary mode.
w+ Opens a file for writing and reading. It overwrites the file if it exists.
a Opens a file for appending. The file pointer is at the end.
x Creates a new file. It raises an error if the file already exists.

Example of opening a file in read mode:

fileptr = open("file.txt", "r")
if fileptr:
    print("File opened successfully")

Closing a File

It’s essential to close a file after performing operations to free up system resources. Use the close() method to close the file.

Syntax:

fileptr.close()

Alternatively, you can use the with statement, which automatically closes the file after the operations are completed.

Example using with statement:

with open("file.txt", "r") as fileptr:
    data = fileptr.read()
    print(data)
# No need to explicitly close the file

Reading Files

To read the contents of a file, Python offers several methods:

read(): Reads the entire file or a specified number of characters.

readline(): Reads a single line from the file.

readlines(): Reads all the lines and returns them as a list.

Example:

with open("file.txt", "r") as fileptr:
    print(fileptr.read()) # Reads the whole file
    print(fileptr.readline()) # Reads one line
    print(fileptr.readlines()) # Returns all lines as a list

Writing to Files

To write data into a file, open it in write or append mode. If the file doesn’t exist, Python will create it.

Example:

with open("file.txt", "w") as fileptr:
    fileptr.write("Hello, World!")

Appending to a file:

with open("file.txt", "a") as fileptr:
    fileptr.write("\nAppended text")

File Pointer Position

The seek() method allows you to move the file pointer to a specific location, while tell() returns the current position of the file pointer.

Example:

with open("file.txt", "r") as fileptr:
    print(fileptr.tell())     # Current position
    fileptr.seek(5)     # Move pointer to 5th byte
    print(fileptr.read())     # Reads from 5th byte onwards

OS Module for File Operations

The os module in Python allows interaction with the operating system for file-related operations, such as renaming and deleting files.

Renaming a file:

import os
os.rename("old_file.txt", "new_file.txt")

Removing a file:

import os
os.remove("file.txt")

Common File Methods

Method Description
file.close() Closes the opened file.
file.read() Reads the file content.
file.write() Writes data to the file.
file.seek() Moves the file pointer to a specific position.
file.tell() Returns the current position of the file pointer.
file.readlines() Returns a list of lines in the file.

Summary:

Python file handling simplifies working with files. It allows for efficient file manipulation, including reading, writing, appending, and modifying file pointers. With features like the with statement and the os module, Python provides a robust environment for managing files across different platforms.