PCAP Exam QuestionsBrowse all questions from this exam

PCAP Exam - Question 106


What is the expected output of the following code if there is no file named non_existing_file inside the working directory?

Show Answer
Correct Answer: D

The code snippet attempts to open a file named 'non_existing_file' in write mode ('w'). This action will succeed because opening a file in write mode creates the file if it does not exist. Consequently, the code prints '1'. However, the following line attempts to read from the file using readline(), which is not allowed in write mode and raises an IOError. Therefore, the print statement in the except block executes, printing '3'. The final output of the code is '1 3'.

Discussion

12 comments
Sign in to comment
vlobachevskyOption: D
Oct 11, 2021

D is correct

mazimir
Oct 15, 2021

Agree, D is correct: try: f = open("linije","w") print(1, end="") s = f.readline() print(2, end="") except IOError as error: print(3, end="") else: f.close() print(4,end="")

macxszOption: D
May 4, 2022

answer: D. 1 3

Noarmy315Option: D
Jan 2, 2022

D s = f.readline() --> io.UnsupportedOperation: not readable

MTLEOption: A
Apr 25, 2022

There is no IO error as w creates a new file. The only operation which raises IO error is either r or r+

macxsz
Apr 29, 2022

Ioerror since variable was open with w not r

Damon54Option: D
Feb 8, 2024

The IOError exception is raised by the line s = f.readline() because the file was opened in write mode ('w'), and readline() tries to read from a file opened in write mode, which is not allowed.

BaldridgeOption: D
May 31, 2022

D D D D D D D

JnanadaOption: D
Aug 19, 2022

It will give IOError. So answer is D

MallieOption: D
Dec 21, 2022

How can the 'Suggested answer' C ever be correct? That doesn't make any sense. Answer is D

9prayerOption: D
Feb 5, 2023

D is correct

dicksonpwcOption: D
Apr 25, 2023

D is correct answer

Janpcap123Option: D
Sep 1, 2023

The correct and only answer is D: 1 3

mplopezOption: D
Sep 8, 2023

The correct answer is D 1 3