Reading Time: 1 minutes
Emulating the 'head' command of Unix in Python
Emulating the 'head' command of Unix in Python: In Unix, the head -n fileName command displays the first n lines of the file fileName. Write a program in Python to emulate the same functionality.
Emulating the 'head' command of Unix in Python
# Ask the user for the filename whose head is to be displayed, and the number of lines comprising the head. |
# Output the first whatever-the-input lines. |
fileName = input ( 'Please enter the name of the file you wish view the head of: ' ) |
numberOfLines = int ( input ( 'Please enter the number of lines in the head that you wish to view: ' )) |
|
fileHandler = open ( fileName, 'r' ) |
|
# list to store the head |
lines = [] |
|
# using a while loop and readline() function, read only a fixed number of lines and append to above list |
while len (lines) < numberOfLines: |
lines.append(fileHandler.readline()) |
|
fileHandler.close() |
|
# Some text to replicate Unix command syntax. |
print ( '\nExecuting command: head -' + str (numberOfLines) + " " + fileName + "\n" ) |
|
# displaying the head |
for line in lines: |
print (line, end = "") |
Try it here.