PCAP Exam QuestionsBrowse all questions from this exam

PCAP Exam - Question 107


What is the expected output of the following code if the file named existing_text_file is a non-zero length text file located inside the working directory?

Show Answer
Correct Answer: B

The code opens the file 'existing_text_file' in write mode ('w'), which truncates the file to zero-length before any read operation can be performed. Since the file is now empty, attempting to read from it returns an empty list of lines. Therefore, the length of this list 'd' will be zero, and thus it prints 0.

Discussion

3 comments
Sign in to comment
macxszOption: B
May 4, 2022

answer: B. -1

MokelOption: C
Apr 23, 2022

Shouldn't it be (c)?

macxsz
Apr 29, 2022

It cant be read because it was open with w

Jos015Option: B
Nov 7, 2023

try: f = open('file.txt','w') d = f.readline() print(len(d)) f.close() except IOError: print(-1) Read with 'r' try: f = open('file.txt','r') d = f.readline() print(len(d)) f.close() except IOError: print(-1)