File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely and efficiently.
Opening a File in Python
To open a file we can use open()
function, which requires file path and mode as arguments:
Python
# Open the file and read its contents
with open('geeks.txt', 'r') as file:
This code opens file named geeks.txt.
File Modes in Python
When opening a file, we must specify the mode we want to which specifies what we want to do with the file. Here’s a table of the different modes available:
Mode | Description | Behavior |
---|
r | Read-only mode. | Opens the file for reading. File must exist; otherwise, it raises an error. |
---|
rb | Read-only in binary mode. | Opens the file for reading binary data. File must exist; otherwise, it raises an error. |
---|
r+ | Read and write mode. | Opens the file for both reading and writing. File must exist; otherwise, it raises an error. |
---|
rb+ | Read and write in binary mode. | Opens the file for both reading and writing binary data. File must exist; otherwise, it raises an error. |
---|
w | Write mode. | Opens the file for writing. Creates a new file or truncates the existing file. |
---|
wb | Write in binary mode. | Opens the file for writing binary data. Creates a new file or truncates the existing file. |
---|
w+ | Write and read mode. | Opens the file for both writing and reading. Creates a new file or truncates the existing file. |
---|
wb+ | Write and read in binary mode. | Opens the file for both writing and reading binary data. Creates a new file or truncates the existing file. |
---|
a | Append mode. | Opens the file for appending data. Creates a new file if it doesn’t exist. |
---|
ab | Append in binary mode. | Opens the file for appending binary data. Creates a new file if it doesn’t exist. |
---|
a+ | Append and read mode. | Opens the file for appending and reading. Creates a new file if it doesn’t exist. |
---|
ab+ | Append and read in binary mode. | Opens the file for appending and reading binary data. Creates a new file if it doesn’t exist. |
---|
x | Exclusive creation mode. | Creates a new file. Raises an error if the file already exists. |
---|
xb | Exclusive creation in binary mode. | Creates a new binary file. Raises an error if the file already exists. |
---|
x+ | Exclusive creation with read and write mode. | Creates a new file for reading and writing. Raises an error if the file exists. |
---|
xb+ | Exclusive creation with read and write in binary mode. | Creates a new binary file for reading and writing. Raises an error if the file exists. |
---|
For this article we are using text file with text:
Hello world
GeeksforGeeks
123 456
Reading a File
Reading a file can be achieved by file.read() which reads the entire content of the file. After reading the file we can close the file using file.close() which closes the file after reading it, which is necessary to free up system resources.
Example: Reading a File in Read Mode (r)
Python
file = open("geeks.txt", "r")
content = file.read()
print(content)
file.close()
Output:
Hello world
GeeksforGeeks
123 456
Reading a File in Binary Mode (rb)
Python
file = open("geeks.txt", "rb")
content = file.read()
print(content)
file.close()
Output:
b'Hello world\r\nGeeksforGeeks\r\n123 456'
Writing to a File
Writing to a file is done using file.write() which writes the specified string to the file. If the file exists, its content is erased. If it doesn’t exist, a new file is created.
Example: Writing to a File in Write Mode (w)
Python
file = open("geeks.txt", "w")
file.write("Hello, World!")
file.close()
Writing to a File in Append Mode (a)
It is done using file.write() which
adds the specified string to the end of the file without erasing its existing content.
Example: For this example, we will use the Python file created in the previous example.
Python
# Python code to illustrate append() mode
file = open('geek.txt', 'a')
file.write("This will add this line")
file.close()
Closing a File
Closing a file is essential to ensure that all resources used by the file are properly released. file.close()
method c
loses the file and ensures that any changes made to the file are saved.
Python
file = open("geeks.txt", "r")
# Perform file operations
file.close()
Using with
Statement
with
statement is used for resource management. It ensures that file is properly closed after its suite finishes, even if an exception is raised. with open() as method automatically handles closing the file once the block of code is exited, even if an error occurs. This reduces the risk of file corruption and resource leakage.
Python
with open("geeks.txt", "r") as file:
content = file.read()
print(content)
Output:
Hello, World!
Appended text.
Handling Exceptions When Closing a File
It’s important to handle exceptions to ensure that files are closed properly, even if an error occurs during file operations.
Python
try:
file = open("geeks.txt", "r")
content = file.read()
print(content)
finally:
file.close()
Output:
Hello, World!
Appended text.
Advantages of File Handling in Python
- Versatility : File handling in Python allows us to perform a wide range of operations, such as creating, reading, writing, appending, renaming and deleting files.
- Flexibility : File handling in Python is highly flexible, as it allows us to work with different file types (e.g. text files, binary files, CSV files , etc.) and to perform different operations on files (e.g. read, write, append, etc.).
- User – friendly : Python provides a user-friendly interface for file handling, making it easy to create, read and manipulate files.
- Cross-platform : Python file-handling functions work across different platforms (e.g. Windows, Mac, Linux), allowing for seamless integration and compatibility.
Disadvantages of File Handling in Python
- Error-prone: File handling operations in Python can be prone to errors, especially if the code is not carefully written or if there are issues with the file system (e.g. file permissions, file locks, etc.).
- Security risks : File handling in Python can also pose security risks, especially if the program accepts user input that can be used to access or modify sensitive files on the system.
- Complexity : File handling in Python can be complex, especially when working with more advanced file formats or operations. Careful attention must be paid to the code to ensure that files are handled properly and securely.
- Performance : File handling operations in Python can be slower than other programming languages, especially when dealing with large files or performing complex operations.
File Handling in Python – FAQs
What is Python file handling?
Python file handling refers to the process of working with files on the filesystem. It involves operations such as reading from files, writing to files, appending data and managing file pointers.
What are the types of files in Python?
In Python, files can broadly be categorized into two types based on their mode of operation:
- Text Files : These store data in plain text format. Examples include
.txt
files. - Binary Files : These store data in binary format, which is not human-readable. Examples include images, videos and executable files.
What are the 4 file handling functions?
The four primary functions used for file handling in Python are:
open()
: Opens a file and returns a file object. read()
: Reads data from a file. write()
: Writes data to a file. close()
: Closes the file, releasing its resources.
Why is file handling useful?
File handling is essential for tasks such as data storage, retrieval and manipulation. It allows Python programs to interact with external files, enabling data persistence, configuration management, logging and more complex operations like data analysis and processing.
What is tell()
in Python file handling?
In Python file handling, tell()
is a method of file objects that returns the current position of the file pointer (cursor) within the file. It returns an integer representing the byte offset from the beginning of the file where the next read or write operation will occur.
Here’s a simple example demonstrating the tell()
method:
# Open a file in read mode
file = open('example.txt', 'r')
# Read the first 10 characters
content = file.read(10)
print(content)
# Check the current position of the file pointer
position = file.tell()
print("Current position:", position)
# Close the file
file.close()
In this example:
file.read(10)
reads the first 10 characters from the file. file.tell()
returns the current position of the file pointer after reading.
Similar Reads
Packing and Unpacking Arguments in Python
Python provides the concept of packing and unpacking arguments, which allows us to handle variable-length arguments efficiently. This feature is useful when we donât know beforehand how many arguments will be passed to a function. Packing ArgumentsPacking allows multiple values to be combined into a
3 min read
First Class functions in Python
First-class function is a concept where functions are treated as first-class citizens. By treating functions as first-class citizens, Python allows you to write more abstract, reusable, and modular code. This means that functions in such languages are treated like any other variable. They can be pas
2 min read
Python Closures
In Python, a closure is a powerful concept that allows a function to remember and access variables from its lexical scope, even when the function is executed outside that scope. Closures are closely related to nested functions and are commonly used in functional programming, event handling and callb
3 min read
Decorators in Python
In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
Help function in Python
In Python, the help() function is a built-in function that provides information about modules, classes, functions, and modules. In this article, we will learn about help function in Python. help() function in Python SyntaxSyntax: help([object]) Parameters (Optional) : Any object for which we want so
6 min read
Python | __import__() function
While writing a code, there might be a need for some specific modules. So we import those modules by using a single-line code in Python. But what if the name of the module needed is known to us only during runtime? How can we import that module? One can use Python's inbuilt __import__() function. It
3 min read
Python Classes and Objects
A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type. Classes are created using class k
6 min read
Constructors in Python
In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
Destructors in Python
Constructors in PythonDestructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when
7 min read
Inheritance in Python
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
7 min read