Beginner Level
Intermediate Level
Advanced Level
Introduction
Python is a popular programming language that is widely used in advanced analytics and data science. One of the most basic yet essential tasks in data processing is being able to read data from a file, which is why understanding how to read a file in Python is crucial. This tutorial will explore the different approaches available to read files in Python programming language, including using the open() function, 'with' statement, and the read()
and readline()
methods. By the end of this tutorial, you should have a solid foundation in reading files in Python that you can use in your data processing workflow.
Table of Contents :
- Opening a file in read mode
- Python file read methods
- Python read() Method
- Python readline() Method
- read first N lines from a file
- read entire file
- read first and the Last line
- Python readlines() Method
- read first N lines from a file
- read the last N lines of a file
- read N bytes from the file
- Reading a file using the with statement in python
- Reading and Writing to the same file
- Reading a binary file in Python
- Reading file in reverse order in Python
Opening a file in read mode
- We can read a file in python by opening the file in read mode.
- To open a file in read mode, the access_mode (second argument of the open function) should be for read operation.
- Different access mode values for reading the file in Python :
`r` | Read mode, used to open a file for reading text data by default. |
`rb` | Binary read mode, used to read binary data from a file. |
`r+` | Read and write mode, used to open a file for both reading and writing. |
Python file read methods :
- Different functions for reading a file in python :
- read(): Reads the entire content of a file into a single string.
- readline(): Reads a single line from a file.
- readlines(): Reads all lines of a file into a list.
- Steps for Reading a File in Python :
- Open a file in read mode using the
open()
method. - Use one of the read methods listed above to read the file.
- Close the file using the
close()
method.
- Open a file in read mode using the
Python read() Method :
- We can use the read method in python to read a file.
- The syntax of using the
read()
method is :fileObject.read( size )
- The
read()
method takes an optional numeric argumentsize
which indicates the number of bytes to be read from the file. - When the
size
parameter is omitted or is negative, the entire contents of the file will be read and returned. - The
read()
method returns the contents of the file as a string (in text mode) or bytes object (in binary mode) - Code Sample :
file = open("example.txt", "r")
print(file.read())
file.close()
How to read N bytes from the file :
- We can read the first n of bytes from a file by passing the optional integer size parameter.
- This block of code reads the first 10 bytes of a file, using the
read()
method. - Code Sample :
with open("example.txt", "r") as file:
bytes = file.read(10)
print(bytes)
Python readline() Method :
- We can also use the
readline()
method in python to read a file. - The syntax of using the
readline()
method is :fileObject.readline( size )
- The
readline()
method takes an optional numeric argumentsize
which indicates the number of bytes from the line to return. - This method reads the file line by line until the end of the file is reached.
- The
readline()
method returns an empty string when the end of the file has been reached - Code Sample :
file = open("example.txt", "r")
print(file.readline())
file.close()
How to read first N lines from a file using readline() :
- The
readline()
method reads the content of the file line by line. - We can then use a loop in python to iterate over the first n lines of the file .
- The code sample below iterates over the first 15 lines of the file and prints them on the console.
- Code Sample :
file = open("example.txt", "r")
for i in range(15):
print(file.readline())
file.close()
How to read entire file using readline()
- This block of code reads the entire file line by line using a while loop,
- The
readline()
method is called repeatedly until the end of the file is reached. - We know that the
readline()
method returns an empty string when the end of the file has been reached. - This can be used to terminate the loop when we reach the end of the loop.
- Code Sample :
file = open("example.txt", "r")
while True:
line = file.readline()
if not line:
break
print(line)
file.close()
How to read first and the last line using readline() :
- We can use the indexing syntax to read desired line through the
readline()
method. - This example reads the first and last lines of the file using the
readline()
method. - Code Sample :
with open("example.txt", "r") as file:
first_line = file.readline()
last_line = file.readlines()[-1]
print(first_line)
print(last_line)
Python readlines() method : reading file into list
- The
readlines()
method reads all the lines of a text file into a list, - Each line of text becomes an element of the list.
- We can then iterate over the list to get the lines of the text.
- The
readlines()
method takes an optional hint parameter which limits the number of lines that should be returned. - Code Sample :
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line)
How to read first N lines from a file using readlines() method :
- We know that
readlines()
method returns a list containing the lines of the text as list elements. - We can use list slicing operation to get the first n elements of the list.
- This code sample below reads the first 5 lines from a file.
- Code Sample :
with open("example.txt", "r") as file:
for line in file.readlines()[:5]:
print(line)
How to read the last N lines of a file using readlines() method :
- List slicing can also be used to read the last n lines of a file.
- This example reads the last 5 lines from a file using list slicing.
- Code Sample :
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines[-5:]:
print(line)
Reading a file using the with statement in python
- The
with
statement is a more elegant way of reading a file, as - it takes care of closing the file after the code block has finished executing.
- Code Sample :
with open("example.txt", "r") as file:
print(file.read())
Reading and Writing to the same file
- We can pass the ‘r+’ access_mode to the open() method to perform both the read and write operations on the file simultaneously.
- This code reads data from a file and appends an extra line to it, using the
read()
andwrite()
methods in combination. - Code Sample :
with open("example.txt", "r+") as file:
data = file.read()
file.write("\nThis is another line.")
Reading a binary file in Python :
- We can pass the ‘rb’ access mode to the open() function to read a binary file.
- This block of code reads binary data from a file using the `rb` mode.
- It reads the entire file into a bytes object.
- Code Sample :
with open("example.png", "rb") as file:
data = file.read()
print(data)
Reading file in reverse order in python
- The
reversed()
function in python can be used to read the file in reverse order. - This block of code reads a text file in a reverse order by iterating over the file in reversed order.
- Code Sample :
with open("example.txt", "r") as file:
lines = file.readlines()
for line in reversed(lines):
print(line.strip())
Prev. Tutorial : Opening a file
Next Tutorial : Writing to a file