Skip to Content

PCAP-31-03: Python File I/O Reading Zero-Length Files Detailed Explanation

Learn how Python handles reading zero-length files using the open() and readline() functions. Discover the expected output and potential exceptions in this comprehensive guide.

Table of Contents

Question

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

try:
f = open('zero_length_existing_file', 'rt')
d = f.readline()
print(len(d))
f.close()
except IOError:
print(-1)

A. 2
B. -1
C. an errno value corresponding to file not found
D. 0

Answer

D. 0

Explanation

In the provided code, the file named “zero_length_existing_file” is opened in read text mode (‘rt’) using the open() function. Since the file exists and is a zero-length file, the open() function will not raise an IOError exception.

The readline() function is then called on the file object f to read the first line of the file. However, since the file is empty and has no content, readline() will return an empty string (”).

Next, the len() function is used to calculate the length of the empty string returned by readline(). The length of an empty string is 0.

Finally, the print() function is called with the length of the empty string, which is 0. Therefore, the expected output of the code is 0.

The except block is not executed in this case because no IOError exception is raised during the file operations.

It’s important to note that if the file “zero_length_existing_file” did not exist in the working directory, an IOError exception would be raised by the open() function, and the code would jump to the except block, printing -1 as the output.

Python Institute PCAP-31-03 certification exam practice question and answer (Q&A) dump with detail explanation and reference available free, helpful to pass the Python Institute PCAP-31-03 exam and earn Python Institute PCAP-31-03 certification.