In: Computer Science
please write simple python code
Write a program to replicate the behavior of UNIX utility “tail”. It takes one or more files and displays requested number of lines from the ending. If number is not specified, then it print 10 lines by default.
Below is the code for mentioned problem statement:
Since tail command will select the n lines from end of the file.
def tail(*args, length=10):
for file_name in args:
try:
with
open(file_name, 'r') as infile:
actualLength
= length
line
= infile.readlines()
print(file_name)
if
len(line) < actualLength:
actualLength
= len(line)
for
index in range(len(line) - actualLength, len(line)):
print(line[index].strip())
except:
print('Could
not read file: {}'.format(file_name))
if __name__ == '__main__':
tail('tail.txt', length=2)
Note: Kindly like and upvote the answer, if it helped
you. In case of any query, just comment. I would be very
happy to resolve all your queries.
Please find the screenshots of code and output.