Given data in text file "rhymes.txt" as follows:
Johny Johny Yes Papa
Eating Sugar No Papa
Telling a lie No Papa
Open your mouth Ha Ha Ha
Find the output for the following code:
my1=open("rhymes.txt","r")
data=my1.read(10)
print(data)
my1.close()
Given data in text file "rhymes.txt" as follows:
Johny Johny Yes Papa
Eating Sugar No Papa
Telling a lie No Papa
Open your mouth Ha Ha Ha
Find the output for the following code:
my1=open("rhymes.txt","r")
data=my1.read(10)
print(data)
my1.close()
Solution
read(10) reads the first 10 characters of the file, counting spaces too, and not 10 words.
| Characters | Count |
|---|---|
| J o h n y | 5 |
| (space) | 6 |
| J o h n | 10 |
So the output is Johny John.
Option 4: "Johny Johny" has 11 characters, so it needs read(11).
Option 1: this would need read() with no argument, which returns the whole file, and even then it would not stop at "Telling a".
Option 2: read() returns a plain string, so no square brackets are printed.
readline() reads one line and readlines() returns a list of lines, but read(n) always reads exactly n characters.
Related questions:
2026: 19 May Shift 1
2026: 23 May Shift 2
2025: 27 May Shift 2