File Handling in Python

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

File handling in Python is a powerful and versatile tool that can be used to perform a wide range of operations. However, it is important to carefully consider the advantages and disadvantages of file handling when writing Python programs, to ensure that the code is secure, reliable, and performs well.

In this article we will explore Python File Handling, Advantages, Disadvantages and How open, write and append functions works in python file.

Python File Handling

Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, like other concepts of Python, this concept here is also easy and short.

To understand the core concept of Python File Handling you can go through the our Python Self Paced Course , which gives you all the basic and advanced concepts of Python.

Python treats files differently as text or binary and this is important. Each line of code includes a sequence of characters, and they form a text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new one has begun. Let’s start with the reading and writing files.

Advantages of File Handling in Python

  • Versatility : File handling in Python allows you 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 you 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.

For this article, we will consider the following ” geeks.txt ” file as an example.

Hello world
GeeksforGeeks
123 456

Python File Open

Before performing any operation on the file like reading or writing, first, we have to open that file. For this, we should use Python’s inbuilt function open() but at the time of opening, we have to specify the mode, which represents the purpose of the opening file.

f = open(filename, mode)

Where the following mode is supported:

  1. r: open an existing file for a read operation.
  2. w: open an existing file for a write operation. If the file already contains some data, then it will be overridden but if the file is not present then it creates the file as well.
  3. a: open an existing file for append operation. It won’t override existing data.
  4. r+: To read and write data into the file. This mode does not override the existing data, but you can modify the data starting from the beginning of the file.
  5. w+: To write and read data. It overwrites the previous file if one exists, it will truncate the file to zero length or create a file if it does not exist.
  6. a+: To append and read data from the file. It won’t override existing data.

Working in Read mode

There is more than one way to How to read from a file in Python . Let us see how we can read the content of a file in read mode.

Example 1: The open command will open the Python file in the read mode and the for loop will print each line present in the file.

Python
# a file named "geek", will be opened with the reading mode.
file = open('geek.txt', 'r')

# This will print every line one by one in the file
for each in file:
    print (each)

Output:

Hello world
GeeksforGeeks
123 456

Example 2: In this example, we will extract a string that contains all characters in the Python file then we can use file.read() .

Python
# Python code to illustrate read() mode
file = open("geeks.txt", "r") 
print (file.read())

Output:

Hello world
GeeksforGeeks
123 456

Example 3: In this example, we will see how we can read a file using the with statement in Python.

Python
# Python code to illustrate with()
with open("geeks.txt") as file:  
    data = file.read() 

print(data)

Output:

Hello world
GeeksforGeeks
123 456

Example 4: Another way to read a file is to call a certain number of characters like in the following code the interpreter will read the first five characters of stored data and return it as a string:

Python
# Python code to illustrate read() mode character wise
file = open("geeks.txt", "r")
print (file.read(5))

Output:

Hello

Example 5: We can also split lines while reading files in Python. The split() function splits the variable when space is encountered. You can also split using any characters as you wish.

Python
# Python code to illustrate split() function
with open("geeks.txt", "r") as file:
    data = file.readlines()
    for line in data:
        word = line.split()
        print (word)

Output:

['Hello', 'world']
['GeeksforGeeks']
['123', '456']

Creating a File using the write() Function

Just like reading a file in Python, there are a number of ways to Writing to file in Python . Let us see how we can write the content of a file using the write() function in Python.

Working in Write Mode

Let’s see how to create a file and how the write mode works.

Example 1: In this example, we will see how the write mode and the write() function is used to write in a file. The close() command terminates all the resources in use and frees the system of this particular program.

Python
# Python code to create a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

Output:

This is the write commandIt allows us to write in a particular file

Example 2: We can also use the written statement along with the  with() function.

Python
# Python code to illustrate with() alongwith write()
with open("file.txt", "w") as f: 
    f.write("Hello World!!!") 

Output:

Hello World!!!

Working of Append Mode

Let us see how the append mode works.

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()

Output:

This is the write commandIt allows us to write in a particular fileThis will add this line

There are also various other commands in Python file handling that are used to handle various tasks:

rstrip(): This function strips each line of a file off spaces from the right-hand side.
lstrip(): This function strips each line of a file off spaces from the left-hand side.

It is designed to provide much cleaner syntax and exception handling when you are working with code. That explains why it’s good practice to use them with a statement where applicable. This is helpful because using this method any files opened will be closed automatically after one is done, so auto-cleanup.

Implementing all the functions in File Handling

In this example, we will cover all the concepts that we have seen above. Other than those, we will also see how we can delete a file using the remove() function from Python os module .

Python
import os

def create_file(filename):
    try:
        with open(filename, 'w') as f:
            f.write('Hello, world!\n')
        print("File " + filename + " created successfully.")
    except IOError:
        print("Error: could not create file " + filename)

def read_file(filename):
    try:
        with open(filename, 'r') as f:
            contents = f.read()
            print(contents)
    except IOError:
        print("Error: could not read file " + filename)

def append_file(filename, text):
    try:
        with open(filename, 'a') as f:
            f.write(text)
        print("Text appended to file " + filename + " successfully.")
    except IOError:
        print("Error: could not append to file " + filename)

def rename_file(filename, new_filename):
    try:
        os.rename(filename, new_filename)
        print("File " + filename + " renamed to " + new_filename + " successfully.")
    except IOError:
        print("Error: could not rename file " + filename)

def delete_file(filename):
    try:
        os.remove(filename)
        print("File " + filename + " deleted successfully.")
    except IOError:
        print("Error: could not delete file " + filename)


if __name__ == '__main__':
    filename = "example.txt"
    new_filename = "new_example.txt"

    create_file(filename)
    read_file(filename)
    append_file(filename, "This is some additional text.\n")
    read_file(filename)
    rename_file(filename, new_filename)
    read_file(new_filename)
    delete_file(new_filename)

Output:

File example.txt created successfully.
Hello, world!
Text appended to file example.txt successfully.
Hello, world!
This is some additional text.
File example.txt renamed to new_example.txt successfully.
Hello, world!
This is some additional text.
File new_example.txt deleted successfully.

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.


Previous Article
Next Article

Similar Reads

Inventory Management with File handling in Python
Inventory management is a crucial aspect of any business that deals with physical goods. Python provides various libraries to read and write files, making it an excellent choice for managing inventory. File handling is a powerful tool that allows us to manipulate files on a computer's file system using programming languages like Python. In this art
5 min read
Handling File Uploads via CGI
In this article, we will explore how we can handle file uploads via CGI (Common Gateway Interface) script on Windows machines. We will develop a form in which there will be the functionality of uploading the file, when the user uploads the file and submits the form, the data is been passed to the CGI script and the file that is uploaded will get st
6 min read
Python - Get file id of windows file
File ID is a unique file identifier used on windows to identify a unique file on a Volume. File Id works similar in spirit to a inode number found in *nix Distributions. Such that a fileId could be used to uniquely identify a file in a volume. We would be using an command found in Windows Command Processor cmd.exe to find the fileid of a file. In o
3 min read
How to save file with file name from user using Python?
Prerequisites: File Handling in PythonReading and Writing to text files in Python Saving a file with the user's custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a cop
5 min read
How to convert PDF file to Excel file using Python?
In this article, we will see how to convert a PDF to Excel or CSV File Using Python. It can be done with various methods, here are we are going to use some methods. Method 1: Using pdftables_api Here will use the pdftables_api Module for converting the PDF file into any other format. It's a simple web-based API, so can be called from any programmin
2 min read
How to convert CSV File to PDF File using Python?
In this article, we will learn how to do Conversion of CSV to PDF file format. This simple task can be easily done using two Steps : Firstly, We convert our CSV file to HTML using the PandasIn the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format. Approach: 1. Converting CSV file to HTML using Pandas Framework. P
3 min read
How to create a duplicate file of an existing file using Python?
In this article, we will discuss how to create a duplicate of the existing file in Python. Below are the source and destination folders, before creating the duplicate file in the destination folder. After a duplicate file has been created in the destination folder, it looks like the image below. For automating of copying and removal of files in Pyt
5 min read
Python - Copy all the content of one file to another file in uppercase
In this article, we are going to write a Python program to copy all the content of one file to another file in uppercase. In order to solve this problem, let's see the definition of some important functions which will be used: open() - It is used to open a file in various modes like reading, write, append, both read and write.write() - It is used t
2 min read
How to convert a PDF file to TIFF file using Python?
This article will discover how to transform a PDF (Portable Document Format) file on your local drive into a TIFF (Tag Image File Format) file at the specified location. We'll employ Python's Aspose-Words package for this task. The aspose-words library will be used to convert a PDF file to a TIFF file. Aspose-Words: Aspose-Words for Python is a pot
3 min read
Handling missing keys in Python dictionaries
In Python, dictionaries are containers that map one key to its value with access time complexity to be O(1). But in many applications, the user doesn't know all the keys present in the dictionaries. In such instances, if the user tries to access a missing key, an error is popped indicating missing keys. Handling Missing Keys in Python DictionariesI
4 min read
SQL using Python | Set 3 (Handling large data)
It is recommended to go through SQL using Python | Set 1 and SQL using Python and SQLite | Set 2 In the previous articles the records of the database were limited to small size and single tuple. This article will explain how to write & fetch large data from the database using module SQLite3 covering all exceptions. A simple way is to execute th
4 min read
Handling PostgreSQL BLOB data in Python
In this article, we will learn how to Handle PostgreSQL BLOB data in Python. BLOB is a Binary large object (BLOB) is a data type that can store any binary data.To store BLOB data in a PostgreSQL database, we need to use the Binary Large Object (BLOB) data type.By using the Binary Large Object (BLOB) data type, we can store any binary data in a Post
5 min read
Multiple Exception Handling in Python
Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages. If you can handle different exceptions all using a single block of code, they can be grouped together in a tuple as shown in th
3 min read
Python IMDbPY - Error Handling
In this article we will see how we can handle errors related to IMDb module of Python, error like invalid search or data base error network issues that are related to IMDbPY can be caught by checking for the imdb.IMDbErrorexceptionIn order to handle error we have to import the following from imdb import IMDbError Syntax : try : # code except IMDbEr
2 min read
Handling mails with EZGmail module in Python
EZGmail is a Python module that can be used to send and receive emails through Gmail. It works on top of the official Gmail API. Although EZGmail does not cover everything that can be done with the Gmail API, it makes the common tasks very simple which are a lot more complicated using Google's own API. In this article, we will take a look at how to
4 min read
Handling TypeError Exception in Python
TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise a TypeError. ExamplesThe general causes for TypeError being raised are: 1. Unsupported Operation Betwe
3 min read
Python VLC MediaPlayer – Enabling Mouse Input Handling
In this article we will see how we can enable mouse input handling the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. By input
2 min read
Handling OSError exception in Python
Let us see how to handle OSError Exceptions in Python. OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as "file not found" or "disk full". Below is an example of OSError: Python Code # Importing
2 min read
Handling a thread's exception in the caller thread in Python
Multithreading in Python can be achieved by using the threading library. For invoking a thread, the caller thread creates a thread object and calls the start method on it. Once the join method is called, that initiates its execution and executes the run method of the class object. For Exception handling, try-except blocks are used that catch the ex
3 min read
Handling EOFError Exception in Python
EOFError is raised when one of the built-in functions input() or raw_input() hits an end-of-file condition (EOF) without reading any data. This error is sometimes experienced while using online IDEs. This occurs when we have asked the user for input but have not provided any input in the input box. We can overcome this issue by using try and except
1 min read
Error Handling in Python using Decorators
Decorators in Python is one of the most useful concepts supported by Python. It takes functions as arguments and also has a nested function. They extend the functionality of the nested function. Example: C/C++ Code # defining decorator function def decorator_example(func): print("Decorator called") # defining inner decorator function def
2 min read
Handling timezone in Python
There are some standard libraries we can use for timezones, here we'll use pytz. This library has a timezone class for handling arbitrary fixed offsets from UTC and timezones. Installation pytz is a third-party package that you have to install. To install pytz use the following command - pip install pytz Getting Started After installation import th
4 min read
Handling TOML files using Python
In this article, we will see how we can manipulate TOML files using tomli/tomlib module in Python. What is a TOML file? TOML stands for Tom's Obvious, Minimal Language, here Tom refers to the creator of this language Tom-Preston Werner. It is a file format, especially for files that hold some kind of configuration details, due to obvious semantics
5 min read
Python Arcade - Handling Keyboard Input
In this article, we will discuss how to handle keyboard inputs in Python arcade module. In Arcade, you can easily check which keyboard button is pressed and perform tasks according to that. For this, we are going to use these functions: on_key_press()on_key_release() Syntax: on_key_press(symbol,modifiers)on_key_release (symbol, modifiers) Parameter
4 min read
Python Arcade - Handling Mouse Inputs
In this article, we will learn how we can handle mouse inputs in the arcade module in Python. In Arcade, you can easily handle the mouse inputs using these functions: on_mouse_motion(): Syntax: on_mouse_motion(x, y, dx, dy) Parameters: x : x coordinatey : y coordinatedx : change in x coordinatedy : change in y coordinate on_mouse_press(): Syntax :
3 min read
Exception Handling Of Python Requests Module
Python request module is a simple and elegant Python HTTP library. It provides methods for accessing Web resources via HTTP. In the following article, we will use the HTTP GET method in the Request module. This method requests data from the server and the Exception handling comes in handy when the response is not successful. Here, we will go throug
4 min read
Python Django Handling Custom Error Page
To handle error reporting in Django, you can utilize Django's built-in form validation mechanisms and Django's error handling capabilities. In this article, I'll demonstrate how to implement error handling. If there are errors in the form submission, the user will be notified of the errors. Required Modules Install DjangoCreate Virtual Env Python D
4 min read
Handling Access Denied Error Occurs While Using Subprocess.Run in Python
In Python, the subprocess module is used to run new applications or programs through Python code by creating new processes. However, encountering an "Access Denied" error while using subprocess.run() can be problematic. This error arises due to insufficient permissions for the user or the Python script to execute the intended command. In this artic
5 min read
Dynamic Forms Handling with HTMX and Python Flask
Dynamic forms enhance the user experience by updating the parts of a web page without the full page reload, the powerful library can allow for the AJAX requests and dynamic updates, while Flask can provide a robust backend framework for Python. This article will guide you through integrating the HTMX with Flask to create dynamic forms. HTMX: It can
4 min read
Precision Handling in Python
Python in its definition allows handling the precision of floating-point numbers in several ways using different functions. Most of them are defined under the "math" module. In this article, we will use high-precision calculations in Python with Decimal in Python. Example Input: x = 2.4Output: Integral value of no = 2 Smallest integer value = 2 Gre
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg