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?
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?
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.
answer: B. -1
Shouldn't it be (c)?
It cant be read because it was open with w
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)