SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Files And Exceptions
Exercise:
Programming Exercises
Question:2 | ISBN:9780132576376 | Edition: 2

Question

File Head Display
Write a program that asks the user for the name of a file. The program should display only the first five lines of the file’s contents. If the file contains less than five lines, it should display the file’s entire contents.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

File Head Display python code:

#Prompt and asks the user for the name of a file.
fileName = input("Enter the name of the file: ")

#Read input file data and print only the first five 
#lines of the file’s contents.
#If the file contains less than five lines, 
#it should display the file’s entire contents.
try:
    with open(fileName, 'r') as file:
        lines = file.readlines()
        
        print("The first five lines of the file’s contents:")
        
        if len(lines) <= 5:
            print("".join(lines))
        else:
            print("".join(lines[:5]))

except FileNotFoundError:
    print(f"File '{fileName}' not found.")
except IOError:
    print(f"An error occurred while reading the file '{fileName}'.")

Data in 'numbers.txt':

1
2
3
4
5
6
7

9
10
Data in "inFile.txt":



3

Executed Output 1:

Enter the name of the file: numbers.txt
The first five lines of the file’s contents:
1
2
3
4
5

Executed Output 2:

Enter the name of the file: inFile.txt
The first five lines of the file’s contents:
1 
2 
3

 

0 0

Discussions

Post the discussion to improve the above solution.