Nearby lessons

88 of 159

Python - Read Files

📌 What You Will Learn
  • Read a complete text file using the read() method
  • Read a specified number of characters using read(n)
  • Read one line at a time with readline()
  • Read all lines into a list using readlines()
  • Use the with statement for automatic file closing
  • Track and move the file pointer with tell() and seek()

Reading Character Data from Text Files

We can read character data from a text file by using the following methods.

  • read() - to read total data from the file.
  • read(n) - to read n characters from the file.
  • readline() - to read only one line.
  • readlines() - to read all lines into a list.

Overview of Reading Methods

Method Purpose
read() Reads the complete file.
read(n) Reads a specified number of characters.
readline() Reads one line.
readlines() Reads all lines into a list.

The read() Method

The read() method is used to read the entire content of a text file.

After reading the complete file, the file pointer moves to the end of the file.

🐍Code Cell
1f.read()
Output
No output captured.

Example 1: Read Complete Data from a File

🐍Code Cell
1f = open("abc.txt", "r")
2 
3data = f.read()
4 
5print(data)
6 
7f.close()
Output
sunny
bunny
chinny
vinny

Explanation

  • open("abc.txt", "r") opens the file in read mode and stores the file object in f.
  • f.read() reads the entire file content and stores it in data.
  • print(data) displays all the contents of the file.
  • f.close() closes the file after completing the read operation.

The read(n) Method

The read(n) method is used to read the first n characters from the file.

After reading those characters, the file pointer automatically moves to the next unread position.

🐍Code Cell
1f.read(n)
Output
No output captured.

Example 2: Read the First 10 Characters

🐍Code Cell
1f = open("abc.txt", "r")
2 
3data = f.read(10)
4 
5print(data)
6 
7f.close()
Output
sunny
bunn

Explanation

Here, read(10) reads only the first 10 characters of the file.

The characters sunny\nbunn represent the first 10 characters of abc.txt.

After reading, the file pointer moves to position 10, ready for the next read.

Difference Between read() and read(n)

Method Description
read() Reads the entire file.
read(n) Reads only the specified number of characters.

The readline() Method

The readline() method is used to read only one line from a text file.

Each call to readline() reads the next line from the file.

After reading a line, the file pointer automatically moves to the beginning of the next line.

🐍Code Cell
1f.readline()
Output
No output captured.

Example 3: Read Data Line by Line

🐍Code Cell
1f = open("abc.txt", "r")
2 
3line1 = f.readline()
4print(line1, end='')
5 
6line2 = f.readline()
7print(line2, end='')
8 
9line3 = f.readline()
10print(line3, end='')
11 
12f.close()
Output
sunny
bunny
chinny

Explanation

Each readline() call reads the next line of the file:

  • The first call reads sunny.
  • The second call reads bunny.
  • The third call reads chinny.

The end='' argument prevents print() from adding an extra blank line after each line.

The readlines() Method

The readlines() method reads all lines from the file and returns them as a list.

🐍Code Cell
1f.readlines()
Output
No output captured.

Example 4: Read All Lines into a List

🐍Code Cell
1f = open("abc.txt", "r")
2 
3lines = f.readlines()
4 
5for line in lines:
6 print(line, end='')
7 
8f.close()
Output
sunny
bunny
chinny
vinny

Explanation

f.readlines() reads all lines and stores them in the list lines.

The for loop prints each line one by one.

Example 5: Mixing Reading Methods

This example demonstrates how different reading methods work together while sharing the same file pointer.

🐍Code Cell
1f = open("abc.txt", "r")
2 
3print(f.read(3))
4print(f.readline())
5print(f.read(4))
6print("Remaining data")
7print(f.read())
Output
sun
ny

bunn
Remaining data
y
chinny
vinny

Explanation

The file abc.txt contains the following lines:

sunny
bunny
chinny
vinny
  1. f.read(3) reads the first 3 characters → sun.
  2. f.readline() reads the remaining characters of the current line → ny.
  3. f.read(4) reads the next 4 characters → bunn.
  4. print("Remaining data") displays the message.
  5. f.read() reads all remaining data → y\nchinny\nvinny.

Because every read method uses the same file pointer, the reads continue from where the previous read stopped.

The with Statement

The with statement can be used while opening a file to group file operations within a block.

The advantage of the with statement is that it takes care of closing the file automatically, after completing all operations — even in the case of exceptions. We are not required to close the file explicitly.

🐍Code Cell
1with open("abc.txt", "w") as f:
2 f.write("Durga\n")
3 f.write("Software\n")
4 f.write("Solutions\n")
5 
6 print("Is File Closed: ", f.closed)
7 
8print("Is File Closed: ", f.closed)
Output
No output captured.

Output

Explanation

Inside the with block, the file is still open, so f.closed returns False.

As soon as the block ends, the with statement closes the file automatically, so f.closed returns True.

The tell() Method

We can use the tell() method to return the current position of the cursor (file pointer) from the beginning of the file.

The position (index) of the first character in a file is zero, just like a string index.

🐍Code Cell
1f = open("abc.txt", "r")
2 
3print(f.tell())
4print(f.read(2))
5print(f.tell())
6print(f.read(3))
7print(f.tell())
Output
No output captured.

Output

Explanation

For the file abc.txt containing the lines sunny, bunny, chinny, and vinny:

  1. Initially, the file pointer is at position 0.
  2. f.read(2) reads su and moves the pointer to position 2.
  3. f.read(3) reads nny and moves the pointer to position 5.

tell() always returns the current cursor position from the beginning of the file.

The seek() Method

Along with tell(), Python provides the seek() method to move the file pointer to a specific position.

🐍Code Cell
1f.seek(position)
Output
No output captured.

Difference Between Reading Methods

Method Description
read() Reads the complete file.
read(n) Reads the specified number of characters.
readline() Reads one line at a time.
readlines() Reads all lines and returns a list.
📝 Key Takeaways
  • read() returns the complete file content as a single string
  • read(n) reads only the specified number of characters
  • readline() reads one line, while readlines() returns a list of all lines
  • All reading methods share the same file pointer, which moves forward after every read
  • The with statement closes the file automatically, even when an exception occurs

🧠 Test Your Knowledge

10 Questions
Progress: 0 / 10