Skip to content
Activities · Activity 2.4

Q.Create a file having multiline data and use readline() with an iterator to read the contents of the file line by line

Uttarakhand UbseTextbookSubjective· 2mImportance★★★★★est
18% · 4/22 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

This solution demonstrates how to create a text file with multiple lines of data and then read its contents line by line using the readline() method in Python.

When working with files in Python, the fundamental idea is to open a connection to the file, perform operations (like writing or reading), and then close the connection. For reading files line by line, Python provides several mechanisms, and readline() is one of them, allowing precise control over reading one line at a time.

Creating a Multiline File

First, we need to create a file with some multiline data. This involves opening the file in write mode ('w'), writing the desired content, and then closing the file. Each line of text must be explicitly terminated with a newline character (\n) for it to be recognized as a separate line when read later.

# Define the file name
file_name = "my_multiline_data.txt"

# Data to be written to the file
data_to_write = """This is the first line.
This is the second line, with some more text.
And this is the third and final line of our sample data."""

# Open the file in write mode ('w')
# The 'with' statement ensures the file is automatically closed
with open(file_name, 'w') as file_object:
    file_object.write(data_to_write)

print(f"File '{file_name}' created successfully with multiline data.")

Key Lines Explanation:

  • file_name = "my_multiline_data.txt": This line defines the name of the file we will create and interact with.
  • data_to_write = """...""": This uses a triple-quoted string to define multiline data. Each line break within this string (except the last one if it's not followed by content) will be treated as a \n character when written to the file.
  • with open(file_name, 'w') as file_object:: This is the recommended way to open files.
    • open(file_name, 'w') opens the file named my_multiline_data.txt in write mode. If the file doesn't exist, it's created. If it exists, its contents are truncated (emptied) before writing.
    • The with statement ensures that file_object.close() is automatically called when the block is exited, even if errors occur.
  • file_object.write(data_to_write): This writes the entire data_to_write string into the file.

Reading the File Line by Line using readline()

To read the file line by line using readline(), we open the file in read mode ('r'). The readline() method reads a single line from the file, including the newline character at the end. When it reaches the end of the file, readline() returns an empty string (''). We can use this behavior in a while loop to iterate through all lines.

# Define the file name (same as before)
file_name = "my_multiline_data.txt"

print(f"\nReading contents of '{file_name}' line by line using readline():")

# Open the file in read mode ('r')
with open(file_name, 'r') as file_object:
    line_number = 1
    # Read the first line
    current_line = file_object.readline()

    # Loop until readline() returns an empty string (end of file)
    while current_line:
        print(f"Line {line_number}: {current_line.strip()}") # .strip() removes leading/trailing whitespace, including '\n'
        line_number += 1
        current_line = file_object.readline() # Read the next line

Expected Output:

File 'my_multiline_data.txt' created successfully with multiline data.

Reading contents of 'my_multiline_data.txt' line by line using readline():
Line 1: This is the first line.
Line 2: This is the second line, with some more text.
Line 3: And this is the third and final line of our sample data.

Key Lines Explanation:

  • with open(file_name, 'r') as file_object:: Opens the file in read mode.
  • current_line = file_object.readline(): This is the first call to readline(). It reads the very first line from the file and stores it in the current_line variable.
  • while current_line:: This loop continues as long as current_line is not an empty string. An empty string signifies that the end of the file has been reached.
  • print(f"Line {line_number}: {current_line.strip()}"): …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.