Table of contents
1.
Introduction
2.
Open() Function
2.1.
Modes
3.
Read() mode
3.1.
Examples
4.
Write() mode
4.1.
Example
5.
Append() mode
5.1.
Example
6.
With open() statement in python
6.1.
Examples
6.1.1.
Read using with keyword
6.1.2.
Write using with keyword
7.
Frequently Asked Questions
8.
Key Takeaways
Last Updated: Mar 27, 2024

File Handling in Python

Author Sanjana Yadav
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Python, along with many other programming languages, offers file handling and allows users to read and write files and perform other file-related operations. The idea of file handling has extended to many other languages, but the code is complicated or lengthy. Still, like many others in Python, this concept is quick and straightforward. Python processes file differently based on whether they are text or binary, which is crucial. Each line of code contains a sequence of characters that constitute a text file. Each line of a file is finished by a special character known as the EOL or End of Line character, which can be a comma or a newline character. It terminates the current line and informs the interpreter that a new one has begun.

Recommended topics, Floor Division in Python, and Convert String to List Python

Also Read, python ord

Open() Function

We must first open the file before performing any operation, such as reading or writing. We should use Python's built-in function open() for this, but we must explicitly state the mode that specifies the purpose of the opening file at the time of opening.

file = open(file_name_with_relative_path,mode)

Modes

The modes listed below are supported.

  • r : To open and perform a read operation on an existing file
     
  • w : To open and perform a write operation on an existing file. Existing data will be overridden.
     
  • a : To open and perform an append operation on an existing file. Existing data will not be overridden.
     
  • r+ : To open and perform read and write operations on an existing file. Existing data will not be overridden.
     
  • w+ : To open and perform write and read operations on an existing file. Existing data will be overridden.
     
  • a+ : To open and perform read and append operations on an existing file. Existing data will not be overridden.
     
  • Also see, Merge Sort Python

Read() mode

In Python, there are many ways to read a file. If we want to extract everything from the file, we can use file.read().

Examples

my_file.txt

This is the first line
This is the second line
This is the third line

Code

sample_file = open("my_file.txt", "r")
print(my_file.read())
sample_file.close()
You can also try this code with Online Python Compiler
Run Code

Output

This is the first line
This is the second line
This is the third line

 

The close() command frees the system of this application by terminating all resources in use.

Another method of reading a file is to call a certain number of characters, such as in the following code, which will read the first certain number of characters and return a string.

my_file.txt

Hello to the world of programming
You can also try this code with Online Python Compiler
Run Code

Code

sample_file = open("my_file.txt", "r")
print(my_file.read(12))
sample_file.close()
You can also try this code with Online Python Compiler
Run Code

Output

Hello to the world
You can also try this code with Online Python Compiler
Run Code

Write() mode

Write mode is used to write on an existing file, and if the file does not exist, it’ll create the file with that name for us.

Example

Code

sample_file = open('file.txt', 'w')
# if the file does not exist, 'w' will create a new file, else it will overwrite the existing file
sample_file.write("This is the first line\n")
sample_file.write("This line will write after the first line")
sample_file.close()
You can also try this code with Online Python Compiler
Run Code

file.txt

This is the first line
This line will write after the first line

Append() mode

Append mode is used to append on an existing file, and if the file does not exist, it’ll create the file with that name for us.

Example

file.txt

This is the first line
This line will write after the first line

Code

sample_file = open('file.txt', 'a')
# if the file does not exist, 'a' will create a new file, else it will append to the existing file
sample_file.write("\nThis is the third line\n")
sample_file.write("This line will write after the third line")
sample_file.close()
You can also try this code with Online Python Compiler
Run Code

file.txt

This is the first line
This line will write after the first line
This is the third line
This line will write after the third line

Also read, python filename extensions

With open() statement in python

In Python, the with statement is used in exception handling to make the code clearer and easier to comprehend. It makes it easier to handle common resources such as file streams. This is useful since any open files will be closed automatically when finished using this approach, resulting in auto-cleanup.

Examples

Read using with keyword

file.txt

Hello to the world of programming

Code

with open("file.txt", 'r') as fl:
    print(fl.read(12))
You can also try this code with Online Python Compiler
Run Code

Output

Hello to the world

Write using with keyword

Code

with open("file.txt",'w') as fl:
    fl.write("Write operation using with")
    fl.write(" and open")
You can also try this code with Online Python Compiler
Run Code

file.txt

Write operation using with and open
You can also try this code with Online Python Compiler
Run Code

 

You can practice by yourself with the help of online python compiler.

Must Read Invalid Syntax in Python.

Frequently Asked Questions

  1. What is the distinction between the r+ and w+ modes?
    If the file does not exist, r+ mode will return an error, but w+ mode will create a new file.
     
  2. What's the distinction between readline() and readlines()?
    The distinction between readline() and readlines() is that readline() returns a single line, whereas readlines() returns a list of lines.
     
  3. Each line is terminated by a special character, what is that character in python?
    EOL i.e., End of Line, each line is terminated by this character and ‘\n’ is used in python for line breaks
     
  4. What is the distinction between the write and append modes?
    Append mode appends new data to the end of the file, whereas write mode overwrites existing data.

Key Takeaways

  • Cheers if you reached here! In this blog, we saw and learned File Handling in Python
  • We have also seen different modes such as read, write and append
  • Further, we saw the with keyword which further reduces our problem of closing the file every time after opening.

On the other hand, learning never ceases, and there is always more to learn. So, keep learning and keep growing, ninjas!

Check out this article - String slicing in Python, Fibonacci Series in Python

Check out the Top 100 SQL Problems to get hands-on experience with frequently asked interview questions and land your dream job.

Good luck with your preparation!

Live masterclass