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 CodeExamples
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 CodeCode:
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 CodeHow 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 Codefile.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 Codefile.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 CodeOutput:
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 Codefile.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 CodeAdvantages of File Handling in Python
Python allows you to create, read, write, append, rename, and delete files easily. It supports various file operations across multiple file types.
Python works well with text, binary, and CSV files. It supports reading, writing, and appending operations, making it flexible for different tasks.
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
File handling can lead to errors if file paths are incorrect, files are missing, or permissions are restricted.
Improper file handling can expose your system to security issues, especially when processing file paths from user input.
Advanced operations such as handling large files, file streaming, or custom formats can be complex and require extra care.
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: