98-381 Exam QuestionsBrowse all questions from this exam

98-381 Exam - Question 27


DRAG DROP -

You are writing a function that works with files.

You need to ensure that the function returns None if the file does not exist. If the file does exist, the function must return the first line.

You write the following code:

Exam 98-381 Question 27

In which order should you arrange the code segments to complete the function? To answer, move all code segments from the list of code segments to the answer area and arrange them in the correct order.

Select and Place:

Exam 98-381 Question 27
Show Answer
Correct Answer:
Exam 98-381 Question 27

References: http://effbot.org/zone/python-with-statement.htm

Discussion

6 comments
Sign in to comment
JeffJupiter
Jul 7, 2020

I would think the with and if statement should be swapped. If statement should come first and with statement nested in the if block

Shw7
Jul 14, 2021

True, Question also mentions if file exist

mallecespedes
Jul 22, 2020

import os filename = "ExampleFile.csv" def get_first_line(filename): if os.path.isfile(filename): with open(filename, 'r') as file: return file.readline() else: return None print(get_first_line(filename))

Daan_peacock
Apr 14, 2021

I got a text file named 'test_file.txt' ready to be read. Checking the two options: # Option 1: Results in error import os def get_first_line(filename, mode): with open(filename, 'r') as file: if os.path.isfile(filename): return file.readline() else: return print(get_first_line("test.txt", 'r')) # Option 2: Reads first line import os def get_first_line(filename, mode): if os.path.isfile(filename): with open(filename, 'r') as file: return file.readline() else: pass print(get_first_line("test_file.txt", 'r'))

Viki2405
Oct 7, 2020

import os def get_data(filename,mode): if os.path.isfile(filename): with open(filename,'r') as file: return file.readline() else: return None

hedi12
Mar 18, 2021

i think it's correct too, when we put "with" befor the "if"

Satbabu
Jul 28, 2021

The "if" statement should come before "with" statement, otherwise the code will throw runtime error "FileNotFoundError" if it couldn't find the specified file in "with" statement.