KnowledgeBoat Logo

Computer Science

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()

Python

Python File Handling

3 Likes

Answer

The code will result in an error because at line 3 there is a syntax error. The correct syntax is s2 = obj1.readline().

Working

The corrected code will be:

obj1 = open("poemBTH.txt", "r")
s1 = obj1.readline()
s2 = obj1.readline()
s3 = obj1.read(15)
print(s3)
print(obj1.readline())
obj1.close()
And their fancy
-frozen boundaries.
  1. obj1 = open("poemBTH.txt", "r") — This line opens the file named poemBTH.txt in read mode ("r") and assigns the file object to the variable obj1.
  2. s1 = obj1.readline() — This line reads the first line from the file obj1 and assigns it to the variable s1.
  3. s2 = obj1.readline() — This line reads the next line from the file obj1, starting from the position where the file pointer currently is, which is the beginning of the second line (from the previous readline() call). Then assigns it to the variable s2.
  4. s3 = obj1.read(15) — This line reads the next 15 characters from the file obj1, starting from the position where the file pointer currently is, which is the beginning of third line (from the previous readline() call) and assigns them to the variable s3.
  5. print(s3) — This line prints the contents of s3.
  6. print(obj1.readline()) — This line attempts to read the next line from the file obj1 and print it. However, since the file pointer is already ahead by 15 characters (from the previous read(15) call), this line will start reading from where the file pointer is currently positioned i.e., from "-" up to end of line.
  7. obj1.close() — This line closes the file obj1.

Answered By

1 Like


Related Questions