Practice Question 12
In this question, we will learn how to write a function that reads a file and displays only the alternate lines (1st, 3rd, 5th, etc.). This logic is often used in log analysis to sample data or reduce output size.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To skip lines, we need to know the position (index) of each line. Here is the teacher’s breakdown:
-
Read as a List: We use
f.readlines()to store every line as an element in a list. -
The Step Logic: Instead of a simple
for line in list, we use arange()loop. -
Range Parameters: We start at index
0, go up to thelen(linelist), and use a step of 2. -
Printing: This ensures the loop only picks indices 0, 2, 4, etc. (which correspond to the 1st, 3rd, and 5th lines).
Let’s Code as per the above logic :
def displayAlternateLines():
f = open("log.txt", "r")
linelist = f.readlines()
# We use range(start, stop, step)
# Step 2 means it will skip every second line
for i in range(0, len(linelist), 2):
print(linelist[i].strip())
f.close()
# To call the function:
displayAlternateLines()
Important Notes for Students
Keep these technical points in mind for your Viva:
-
Index vs. Line Number: Remember that computers start counting at
0. So, the “1st line” is at index0, the “3rd line” is at index2, and so on. -
The
strip()function: Sincereadlines()includes the newline character (\n), andprint()adds its own newline, using.strip()prevents your output from having double spacing. -
Even/Odd Logic: If the examiner asks for even lines (2nd, 4th, 6th…), simply change the range to
range(1, len(linelist), 2).
Teacher’s Secret Tip for Exams:
You can also achieve this in just one line using Python’s slicing shortcut! for line in linelist[::2]: print(line.strip()). The [::2] tells Python to take the whole list but skip every second item. Using this in an exam shows you are an advanced Python coder! But as per CBSE might be this solution is not acceptable due to less no of steps.
Want to practice more? If you found this helpful, I have compiled a full list of 30 practice problems just like this one. Each question focuses on a different logic to help you become a pro at File Handling.
Click here to view the full 30-Question Practice Set
Exam Special Recommendation: If you are studying in 12th class and preparing for your board exam, then go for the “Computer Science with Python Sample Paper Book“. It contains 3 previous years’ papers and 7 practice papers solved strictly as per the CBSE pattern. Click here to purchase your copy!