Write a Python function that takes a filename as input and attempts to read and print the first 5 lines. If the file does not exist, return the string “Error: File does not exist”. If the file contains less than 5 lines, print all the lines and return the string “Note: File contains less than 5 lines”.
Example 1:
Input: "file_with_more_than_5_lines.txt" Output: "First 5 lines printed successfully"
Example 2:
Input: "file_with_less_than_5_lines.txt" Output: "Note: File contains less than 5 lines"
Use try-except block to handle FileNotFoundError and handle situation when file has less than 5 lines.
def read_file(filename): try: with open(filename, 'r') as f: for i in range(5): print(f.readline()) return "First 5 lines printed successfully" except FileNotFoundError: return "Error: File does not exist" except: return "Note: File contains less than 5 lines" print(read_file("file_with_more_than_5_lines.txt")) # Output: "First 5 lines printed successfully" print(read_file("file_with_less_than_5_lines.txt")) # Output: "Note: File contains less than 5 lines"
Unlock AI & Data Science treasures. Log in!