176k views
0 votes
Write a program that asks the user for the name of a file. The program should display the first 10 lines of the file on the screen (the "head" of the file). If the file has fewer 12 Advanced File Operations than 10 lines, the entire file should be displayed, with a message indicating the entire file has been displayed.

User Orbeckst
by
8.2k points

1 Answer

6 votes

Final answer:

The task requires creating a program to display the first 10 lines of a user-specified file or the entire file if it's shorter, with an appropriate message. Example code in Python demonstrates file reading and exception handling for a non-existent file.

Step-by-step explanation:

The student's question pertains to writing a program that reads the head of a file - specifically, displaying the first 10 lines or the entire file if it contains fewer than 10 lines. Here's an example code snippet in Python to achieve this:

filename = input('Enter the name of the file: ')
try:
with open(filename, 'r') as file:
for i in range(10):
line = file.readline()
if not line:
print('\\Entire file has been displayed.')
break
print(line, end='')
except FileNotFoundError:
print('File does not exist.')

In this code, the user is prompted to enter the name of a file. The script opens the file and reads it line by line, stops if it reaches the end, and handles the situation where a file might not exist. This is a basic file operation task commonly performed in many programming environments.

User Kathan Shah
by
8.0k points