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.
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
8
9
10
Data in "inFile.txt":
1
2
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