Table of contents
1.
Introduction
2.
How to Open a File in Python with Examples
2.1.
Open() Function
2.2.
open() Function Syntax
2.3.
Types of File Modes
2.4.
Example
3.
Reading Files in Python with Examples
3.1.
Read() mode
3.2.
read() Function Syntax in Python
3.3.
Types of Reading Modes
3.4.
Examples
4.
How to Write to a File in Python with Examples
4.1.
Write() mode
4.2.
write() Function Syntax in Python
4.3.
Types of Writing Modes
4.4.
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.
How to Close a File in Python: Proper File Handling with Examples
7.1.
close() Function: Syntax
8.
Types of Closing Modes
9.
Advantages of File Handling in Python
10.
Disadvantages of File Handling in Python
11.
Frequently Asked Questions
11.1.
What is the distinction between the r+ and w+ modes?
11.2.
What's the distinction between readline() and readlines()?
11.3.
Each line is terminated by a special character, what is that character in python?
11.4.
What is the distinction between the write and append modes?
12.
Conclusion
Last Updated: Aug 22, 2025
Easy

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.

File Handling in Python

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

Also Read, python ord

How to Open a File in Python with Examples

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)

open() Function Syntax

The syntax is: 

open(file_path, mode)


where file_path is the name or path of the file, and mode defines how the file is opened (e.g., read 'r', write 'w').
Using the with statement ensures the file closes automatically after use, preventing memory leaks or file corruption.

Types of File 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

Example

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


This code safely opens 'filename.txt' in read mode and prints its contents. The with statement ensures the file is closed automatically after reading.

Reading Files in Python with Examples

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

read() Function Syntax in Python

Syntax:

file.read(size)


The read() function reads content from a file. If no size is given, it reads the entire file; otherwise, it reads the specified number of bytes or characters. It’s usually used within a with open() block to ensure safe file handling.

Types of Reading Modes

Reading in Text Mode ('r')
This mode is used to read plain text files. It opens the file in text format and returns data as a string. Example:

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


Reading in Binary Mode ('rb')
This mode reads the file in binary format, returning data as bytes. It's commonly used for non-text files like images or videos. Example:

with open('image.jpg', 'rb') as file:
    data = file.read()
    print(data[:10])  # print first 10 bytes
You can also try this code with Online Python Compiler
Run Code

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

How to Write to a File in Python with Examples

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.

write() Function Syntax in Python

Syntax: 

file.write(string)


The write() function writes a string to the file. It does not add a newline automatically—you must include \n if needed. It’s usually used within a with open() block to safely write data and ensure the file is properly closed.

Types of Writing Modes

Write Mode (w)

The write mode (w) is used to create a new file or overwrite the content of an existing file. If the file already exists, all its previous content is erased before writing new data. If the file doesn’t exist, it will be created automatically. This mode is useful when you want a clean start and don’t need the old data. Always use with caution to avoid accidental data loss.
 

Append Mode (a)

The append mode (a) allows you to add new content to the end of an existing file without removing or changing its previous data. If the file does not exist, it is created. This mode is ideal when you want to update logs, save user input, or continue writing where the last session left off—without affecting existing content.

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.

How to Close a File in Python: Proper File Handling with Examples

It is important to learn on how to close a file properly in Python. It covers the importance of freeing system resources, ensuring data is saved, and preventing errors. You’ll also learn three ways to close files: using file.close(), the with statement, and exception handling.

close() Function: Syntax

Syntax:

file.close()
You can also try this code with Online Python Compiler
Run Code


Explanation:
The close() function is used to close a file after completing read or write operations. It ensures that the file is saved properly and system resources are released. Failing to close a file may cause memory leaks or data loss.

Types of Closing Modes

1. Closing a File Using file.close()

The file.close() method is used when a file is opened manually. It is important to call this method after completing file operations. This ensures the file is not locked and system resources are freed. Always use file.close() if you're not using a with block.

Example:

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


2. Using the with Statement

The with statement simplifies file handling by automatically closing the file once the block is exited. This method is cleaner, safer, and avoids forgetting to close the file manually. It also works well with exception handling.

Example:

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


3. Handling Exceptions When Closing a File

You can also handle file closing using a try-finally block. This ensures the file closes even if an error occurs during file operations. It’s helpful when you want both manual control and safe closing.

Example:

try:
    file = open("example.txt", "r")
    content = file.read()
    print(content)
finally:
    file.close()
You can also try this code with Online Python Compiler
Run Code

Advantages of File Handling in Python

  • Versatility

Python allows you to create, read, write, append, rename, and delete files easily. It supports various file operations across multiple file types.
 

  • Flexibility

Python works well with text, binary, and CSV files. It supports reading, writing, and appending operations, making it flexible for different tasks.
 

  • User-Friendly

Python makes file handling simple with readable syntax and built-in functions. Even beginners can perform complex file tasks with ease.
 

  • Cross-Platform Compatibility

Python’s file-handling features work the same on Windows, macOS, and Linux. This ensures code portability across systems.

Disadvantages of File Handling in Python

  • Error-Prone

File handling can lead to errors if file paths are incorrect, files are missing, or permissions are restricted.
 

  • Security Risks

Improper file handling can expose your system to security issues, especially when processing file paths from user input.
 

  • Complexity

Advanced operations such as handling large files, file streaming, or custom formats can be complex and require extra care.
 

  • Performance

When dealing with large files, Python may be slower compared to lower-level languages like C or C++, especially in processing speed.

Frequently Asked Questions

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.

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.

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

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.

Conclusion

  • 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.

Recommended Readings: 

Live masterclass