CBSE Class 12 Computer Science Question 133 of 145

File Handling — Question 13

Back to all questions
13
Question

Question 13

Write a program that counts the number of characters up to the first $ in a text file.

Answer

Let the sample file "myfile.txt" contain the following text:

Hello world! This is a test file.
It contains some characters until the first $ is encountered.
count = 0
with open("myfile.txt", 'r') as file:
    while True:
        char = file.read(1)  
        if char == '$' or not char:  
            break
        count += 1
print(count)
Output
78