Computer Science
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.
Related Questions
Differentiate between "w" and "r" file modes used in Python while opening a data file. Illustrate the difference using suitable examples.
Differentiate between the following :
(i) f = open('diary.txt', 'r')
(ii) f = open('diary.txt', 'w')
If the file 'poemBTH.txt' contains the following poem (by Paramhans Yoganand) :
God made the Earth; Man made confining countries And their fancy-frozen boundaries. But with unfound boundLess Love I behold the borderLand of my India Expanding into the World. HaiL, mother of religions, Lotus, scenic beauty, and sages!
Then what outputs will be produced by both the code fragments given in question1.
Consider the file poemBTH.txt given above (in previous question). What output will be produced by following code fragment ?
obj1 = open("poemBTH.txt", "r") s1 = obj1.readline() s2.readline(10) s3 = obj1.read(15) print(s3) print(obj1.readline()) obj1.close()