Q.(a) Write a Python function that counts and returns the number of digits appearing in the text file "Space.txt". For example, if the file contains : Space exploration has unlocked incredible advancements in technology and science. Since the first moon landing in 1969, space agencies have sent probes to Mars, Jupiter and beyond. The ISS, orbiting Earth at about 400 km, serves as a hub for research. With missions planned for 2030, humanity’s cosmic journey continues! Then the function should return 11.
🔒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 →Part (a)Concept understanding — File Handling Methods
File Handling Methods: A First Look
Think about the last time you saved a document on your computer. You clicked "Save," gave it a name, and later opened it again to continue working. That simple act—storing information so you can retrieve it later—is the entire reason file handling exists. Every time you work with a file, whether it's a Word document, a PDF, or even a photo, you are performing file handling.
At its core, file handling is the process of creating, reading, updating, and deleting files through a computer program. It is how a program talks to the storage on your machine—the hard drive or SSD—rather than just working with data that disappears when you close the program.
The Two Fundamental Modes
When a program wants to work with a file, it must first open that file. Opening a file is like unlocking a drawer: you decide what you want to do with it before you start. There are two basic intentions:
- Reading – You want to look at the contents of the file without changing anything. The file stays exactly as it is.
- Writing – You want to put new content into the file, either by starting fresh (overwriting everything) or by adding to what is already there (appending).
These two intentions define the mode in which you open the file. A file opened for reading cannot be written to, and a file opened for writing cannot be read from—at least not in the simplest approach. This separation exists to prevent accidents: you do not want a program that is supposed to only display your data to accidentally erase it.
In many programming languages, you can open a file in "read and write" mode, but that is a more advanced technique. For a beginner, think of reading and writing as two separate keys that open different locks on the same drawer.
The Lifecycle of a File Operation
Every file handling operation follows a fixed sequence. You cannot skip a step without causing trouble.
- Open the file – You tell the program which file you want and what you intend to do with it (read or write). The program checks whether the file exists (for reading) or whether it can create a new one (for writing).
- Perform the operation – You either read the data from the file into your program's memory, or you write data from your program into the file. This step can happen many times—you might read one line, then another, then another.
- Close the file – You tell the program you are done. This step is crucial. Closing a file saves any changes you made and frees up the file so other programs can use it.
Forgetting to close a file is like leaving a tap running. The file may remain locked, data might not be saved properly, and your program could waste memory. Always close what you open.
Why This Matters for a Commerce or Humanities Student
You might wonder why a student of commerce or humanities needs to understand file handling. The answer is simple: almost every modern business, government office, and research project deals with data stored in files.
- A commerce student analyzing sales records will need to read data from a spreadsheet file, process it, and write the results to a new file.
- A humanities student working with historical documents might need to read text files containing old letters, clean up the formatting, and save the cleaned version.
- Anyone managing a database or a website will encounter file handling when uploading images, generating reports, or backing up information. …
Part (b)Concept understanding — File Input Output Filtering
File Input Output Filtering
Think of a water filter. You pour in tap water, and what comes out is cleaner, purer, and ready to drink. The filter doesn't create new water — it takes what's already there and transforms it by removing impurities or adding something useful.
File Input Output Filtering works on the same principle. It is a way of processing data as it moves from one place to another — typically from an input source (like a file or keyboard) to an output destination (like a file or screen). The "filter" sits in between, reading the incoming data, modifying it in some way, and then writing the modified version out.
The Core Idea
At its simplest, a filter takes a stream of data, performs a transformation on it, and produces a new stream. The transformation could be anything: converting all letters to uppercase, removing blank lines, replacing one word with another, or rearranging the order of records.
The key insight is that the filter does not care where the data came from or where it is going. It only cares about what to do with the data as it passes through. This makes filters reusable — the same filter can work on data from a file, from a user typing at a keyboard, or from the output of another program.
Why It Matters
In the real world, data rarely arrives in the exact format you need. A bank might receive transaction records with dates written as "2024-03-15" but their system expects "15 March 2024". A school might get student lists with names in lowercase but needs them capitalised. A business might export a report with extra blank lines that clutter the final document.
Instead of rewriting entire programs for each of these situations, you can use filters. You take the raw data, run it through the appropriate filter, and get exactly what you need on the other side.
How It Works in Practice
A filter typically follows a simple pattern:
- Read one piece of data (a line, a character, a record)
- Process it according to the rule
- Write the result
- Repeat until there is no more data
This is called a "loop" — the filter keeps doing the same thing over and over until the input runs out. Because it processes data piece by piece rather than loading everything into memory at once, it can handle enormous files without slowing down.
This "read-process-write" cycle is why filters are so efficient. A filter that converts a million-line file to uppercase never holds more than one line in memory at a time. It reads a line, converts it, writes it, and moves on.
Common Types of Filters
Filters can be grouped by what they do to the data:
Transformation filters change the content itself. Converting text to uppercase, replacing British spellings with American ones, or encrypting sensitive information are all transformations.
Selection filters choose which pieces of data to keep and which to discard. A filter that removes all lines containing the word "ERROR" is a selection filter — it lets some data through and blocks the rest.
Formatting filters change the appearance or structure without altering the meaning. Adding line numbers to a document, aligning columns, or inserting page breaks are formatting operations.
Combination filters do more than one thing. A filter might remove blank lines, convert everything to lowercase, and then add a timestamp to each line — all in a single pass.
The Chain Concept
The real power of filtering emerges when you connect filters together. The output of one filter becomes the input to the next. This is called a "pipeline" or "chain."
Imagine you have a raw data file with messy entries. You could:
- First filter: remove blank lines
- Second filter: convert all text to uppercase
- Third filter: sort the lines alphabetically
- Fourth filter: add line numbers
Each filter does one simple job. Together, they produce a clean, numbered, sorted, uppercase document from the original mess. You can rearrange, add, or remove filters without changing any of them individually.
The principle of "one job, done well" is central to filtering. A filter that tries to do everything becomes complex and brittle. A filter that does one thing can be combined with others to achieve almost any result.
A Concrete Example Without Numbers …
Part (a)
Open the file, read its whole content and count characters for which isdigit() is True.
def countDigits():
f = open("Space.txt", "r")
text = f.read()
f.close()
count = 0
for ch in text:
if ch.isdigit():
count += 1
return count
print(countDigits())
``` …
Part (a) reads the file and counts every digit character with isdigit() (returns 11 here); Part (b) splits the file into words and prints those containing the lowercase letter e at least twice.
Part (a)
We must count how many digit characters (0–9) occur in Space.txt.
Approach
- Open the file in read mode and read the entire content into a string.
- Walk over every character;
str.isdigit()isTrueonly for'0'–'9'. - Keep a running counter and return it.
def countDigits():
count = 0
with open("Space.txt", "r") as f:
for ch in f.read():
if ch.isdigit():
count += 1
return count
print(countDigits())
``` …
- CBSE 2024Set 91/41 markMCQQ.Consider the following Python statement: F=open('CONTENT.TXT') Which of the following is an invalid statement in Python? (A) F.seek(1,0) (B) F.seek(0,1) (C) F.seek(0,-1) (D) F.seek(0,2)
›Reveal solutionSolution
The
seek()method in Python's file handling allows you to change the current position of the file pointer, but itswhenceargument, which specifies the reference point, must be one of three specific integer values: 0 (beginning), 1 (current position), or 2 (end of file).In Python, interacting with files is a fundamental aspect of many programs, allowing us to store and retrieve data persistently. The statement
F = open('CONTENT.TXT')is the first step in this process. It opens a file namedCONTENT.TXTin the default read mode ('r') and returns a file object, which we've assigned to the variableF. This file object acts as a gateway, providing methods to perform operations like reading, writing, and, importantly, navigating within the file.One crucial method for navigating within a file is
seek(). Imagine a cursor in a text editor;seek()allows you to move this cursor to a specific location within the file. This is incredibly useful when you need to re-read a part of a file, skip certain sections, or write data at a precise point.The
seek()method takes two arguments:seek(offset, whence).- The
offsetargument specifies the number of bytes to move. This can be a positive or negative integer, depending on thewhenceargument. - The
whenceargument determines the reference point from which theoffsetis calculated. This is where the strict rules apply, and understanding these values is key to usingseek()correctly.
There are only three valid integer values for
whence:0(oros.SEEK_SET): This means theoffsetis relative to the beginning of the file. Whenwhenceis 0, theoffsetmust be a non-negative integer, as you cannot move before the start of the file.1(oros.SEEK_CUR): This means theoffsetis relative to the current file position. Theoffsetcan be positive (to move forward) or negative (to move backward) from the current position.2(oros.SEEK_END): This means theoffsetis relative to the end of the file. Whenwhenceis 2, theoffsetis typically a non-positive integer (0 or negative) to move backward from the end of the file. A positive offset from the end would move beyond the file's actual content.
ImportantThe
whenceargument inF.seek(offset, whence)can only take the integer values 0, 1, or 2. Any other integer value will result in anOSErrororValueError.Now, let's examine the given statements based on these rules: …
- The
- CBSE 2023Set 91/11 markMCQQ.The syntax of seek() is: file_object.seek(offset[,reference_point]) What is the default value of reference_point?(a) 0(b) 1(c) 2(d) 3
›Reveal solutionSolution
The
seek()method changes the file object's current position. Itsreference_pointargument, which specifies the starting point for the offset, defaults to 0 — the beginning of the file. Correct option: (a).When you work with files, the operating system tracks your current position within the file — the "file pointer". The
seek()method lets you move this pointer manually. Its syntax isfile_object.seek(offset[, reference_point]), whereoffsetis the number of bytes to move andreference_pointis the position the offset is measured from.There are three standard reference points:
reference_point Measured from Note 0Beginning of the file Default; offset must be zero or positive 1Current file position Offset may be positive or negative 2End of the file Offset is usually zero or negative Because moving to an absolute position from the start of a file is by far the most common need,
seek()makes0the default. Sof.seek(7)is exactly the same asf.seek(7, 0)— both move the pointer 7 bytes from the beginning. … - CBSE 2023Set 91/41 markMCQQ.The correct syntax of tell() is :(a) tell.file_object()(b) file_object.tell()(c) tell.file_object(1)(d) file_object.tell(1)
›Reveal solutionSolution
In Python file handling, the
tell()method is called on a file object using dot notation, with no arguments — the correct syntax isfile_object.tell().When you work with files in Python, you are essentially moving a cursor through a stream of data. Every time you read or write, that cursor advances. The
tell()method is the tool that tells you exactly where that cursor is at any moment — it returns the current position (as an integer representing bytes from the beginning of the file).The syntax follows the standard object-oriented pattern in Python. A file object — created by
open()— has methods attached to it. You access those methods by writing the object's name, a dot, and then the method name. Sofile_object.tell()is the correct form. No argument is needed inside the parentheses becausetell()simply reports the current position; it does not change it.NoteThe position returned by
tell()is measured in bytes, not characters. For text files, this distinction matters when the file uses multi-byte encodings like UTF-8 — but for most exam purposes, you can treat it as the cursor's offset from the start.Now look at the options given:
- (a)
tell.file_object()— This is wrong because it treatstellas if it were the object andfile_objectas a method. In Python, the object comes first, then the dot, then the method. - (b)
file_object.tell()— This is correct. The file object is the thing that knows its position, andtell()is the method that asks it. …
- (a)
- CBSE 2023Set 91/41 markMCQQ.Q. 17 and 18 are Assertion (A) and Reasoning (R) based questions. Mark the correct choice as(a) Both (A) and (R) are true and (R) is the correct explanation for (A).(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).(c) (A) is true but (R) is false.(d) (A) is false but (R) is true. Assertion (A) : readlines() reads all the lines from a text file and returns the lines along with newline as a list of strings. Reasoning (R) : readline() can read the entire text file line by line without using any looping statements.
›Reveal solutionSolution
The
readlines()method reads all lines into a list, whilereadline()reads one line at a time, requiring a loop to process an entire file.When working with text files in Python, a common task is to read their contents. Python provides several methods for this, each suited for different scenarios. Understanding the nuances of these methods, particularly
readlines()andreadline(), is crucial for efficient and correct file handling. These methods allow us to access the data stored in a file, whether we need it all at once or line by line.The
readlines()method is designed for situations where you need to load the entire content of a text file into memory as a collection of individual lines. When you callreadlines()on an open file object, it performs the following actions:- It reads every single line from the current position in the file until the end of the file is reached.
- It collects these lines into a list.
- Each element in this list is a string, representing one line from the file.
- Crucially, each of these string elements retains the newline character (
\n) at its end, which marks the termination of a line in the text file.
NoteThe newline character (
\n) is an invisible character that signifies the end of a line and causes the cursor to move to the beginning of the next line. Whenreadlines()returns a list of strings, these\ncharacters are included in the strings, unless they are explicitly removed (e.g., usingstrip()).In contrast, the
readline()method operates differently. Its purpose is to read a file one line at a time, which is particularly useful when dealing with very large files that might not fit entirely into memory, or when you need to process each line individually before moving to the next.- When
readline()is called, it reads only the next single line from the file. - It returns this line as a single string.
- Similar to
readlines(), this string also includes the newline character (\n) at its end, if present in the file. - If
readline()is called again, it reads the subsequent line. This sequential reading continues until the end of the file. When the end of the file is reached, subsequent calls toreadline()will return an empty string ('').
ImportantTo read the entire text file line by line using
readline(), you must employ a looping construct, such as awhileloop or aforloop (though aforloop directly over the file object is often more Pythonic for line-by-line iteration). Without a loop,readline()will only ever read the first line (or the next single line if called multiple times manually).Now, let's evaluate the given Assertion and Reasoning: …
🎓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.