[Type B] File Handling – Chapter 5 Sumita Arora

|
Table of Contents

8. Consider the file poemBTH.txt and predict the output of following code fragment. What exactly is the following code fragment doing?

Python
f = open ("poemBTH.txt", "r")
nl = 0
for line in f:
    nl += 1
print(nl)

Answer: The code opens the “poemBTH.txt” file in read mode ("r"), iterates through each line, counts the lines, and finally prints the total number of lines (excluding any empty lines).

Explanation:

  1. Opens the “poemBTH.txt” file in read mode ("r").
  2. Initializes a variable nl (number of lines) to 0.
  3. Uses a for loop to iterate through each line in the file.
  4. Inside the loop, increments the nl variable by 1 for each line encountered.
  5. After iterating through all lines, the code prints the final value of nl, which represents the total number of lines in the file (excluding empty lines).

Here’s the code with some formatting and comments for better understanding:

Python
# Open the file in read mode
f = open("poemBTH.txt", "r")

# Initialize the line counter to 0
nl = 0

# Iterate through each line in the file
for line in f:
    # Increment the line counter by 1
    nl += 1

# Print the total number of lines
print(nl)

# Close the file (very important)
f.close()

Its a good practice to close the file after reading/writing operations. Alternatively, you can use the with statement, which automatically closes the file when the block of code is exited:

Python
with open("poemBTH.txt", "r") as f:
    nl = 0
    for line in f:
        nl += 1
    print(nl)
"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *

One Comment