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.
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 |
|---|
r | Read mode. Opens a file for reading. The file must exist. |
|---|
w | Write mode. Opens a file for writing. Creates a new file if it doesn’t exist or truncates the file if it exists. |
|---|
a | Append mode. Opens a file for appending. Creates a new file if it doesn’t exist. |
|---|
b | Binary mode. Opens a file in binary mode. |
|---|
t | Text mode. Opens a file in text mode. Default mode. |
|---|
x | Exclusive creation mode. Creates a new file and fails if it already exists. |
|---|
r+ | Read and write mode. Opens a file for both reading and writing. The file must exist. |
|---|
w+ | Write and read mode. Opens a file for both writing and reading. Creates a new file if it doesn’t exist or truncates the file if it exists. |
|---|
a+ | Append and read mode. Opens a file for appending and reading. Creates a new file if it doesn’t exist. |
|---|
For this article we are using text file
Hello world
GeeksforGeeks
123 456
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.
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 closes 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
We use two operators * (for tuples) and ** (for dictionaries). Background Consider a situation where we have a function that receives four arguments. We want to make a call to this function and we have a list of size 4 with us that has all arguments for the function. If we simply pass a list to the
5 min read
First Class functions in Python
First class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. A programming language is said to support first-class functions if it treats functions as first-class objects. Python supports the concept of
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
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of a function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it. But before diving deep into de
7 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
Encapsulation in Python
In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage. Table of Content En
6 min read
Polymorphism in Python
Polymorphism is a foundational concept in programming that allows entities like functions, methods or operators to behave differently based on the type of data they are handling. Derived from Greek, the term literally means "many forms". Python's dynamic typing and duck typing make it inherently pol
7 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated
5 min read
File Handling in Python
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 a
6 min read
Reading and Writing to text files in Python
Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL
9 min read
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work. In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we
7 min read
Python Exception Handling
We have explored basic python till now from Set 1 to 4 (Set 1 | Set 2 | Set 3 | Set 4). In this article, we will discuss how to handle exceptions in Python using try, except, and finally statements with the help of proper examples. Error in Python can be of two types i.e. Syntax errors and Excepti
9 min read
User-defined Exceptions in Python with Examples
Prerequisite: This article is an extension to Exception Handling. In this article, we will try to cover How to Define Custom Exceptions in Python with Examples. Example: class CustomError(Exception): pass raise CustomError("Example of Custom Exceptions in Python") Output: CustomError: Example of Cus
4 min read
Python Built-in Exceptions
In Python, exceptions are events that can alter the flow of control in a program. These errors can arise during program execution and need to be handled appropriately. Python provides a set of built-in exceptions, each meant to signal a particular type of error. We can catch exceptions using try and
9 min read
Python Try Except
In Python, errors and exceptions can interrupt the execution of program. Python provides try and except blocks to handle situations like this. In case an error occurs in try-block, Python stops executing try block adn jumps to exception block. These blocks let you handle the errors without crashing
6 min read
Python RegEx
A Regular Expression or RegEx is a special sequence of characters that uses a search pattern to find a string or set of strings. It can detect the presence or absence of a text by matching it with a particular pattern and also can split a pattern into one or more sub-patterns. Regex Module in Python
15+ min read