CBSE Class 12 Computer Science Question 105 of 145

File Handling — Question 1

Back to all questions
1
Question

Question 1

How are following codes different from one another ?

(a)

my_file = open('poem.txt', 'r')
my_file.read()

(b)

my_file = open('poem.txt', 'r') 
my_file.read(100)
Answer

The provided code snippets (a) and (b) are similar in that they both open the file poem.txt in read mode ('r'). However, they differ in how they read the contents of the file:

(a) my_file.read(): This code reads the entire content of the file poem.txt into a single string. It reads until the end of the file (EOF) is reached.

(b) my_file.read(100): This code reads the first 100 characters from the file poem.txt into a string. It reads up to the 100 number of characters or until EOF is reached, whichever comes first.