SoFunction
Updated on 2024-11-07

Python tutorial for printing the first or last few lines of a file

Write a small tool like linux head for use under window.

 

# -*- coding: UTF-8 -*-
#!/usr/bin/python
# by Jakcing 2019.02.17
# print first n lines or last n lines in big file 
 
 
import sys
import getopt
import linecache
 
 
VERSION="1.1"
 
def get_line_count(filename):
 line_count = 0
 file = open(filename,'r+', encoding='utf-8')
 while True:
 buffer = (8192 * 1024 )
 if not buffer:
  break
 line_count += ('\n')
 ()
 return line_count
 
def read_head_line(flist, line_num):
 for file_name in flist:
 print("===%s===" % file_name)
 f = open(file_name, 'r', encoding='utf-8')
 if(f):
  for i in range(line_num):
  print((), end='')
 
 
 
def read_last_line(flist, line_num):
 
 for file_name in flist:
 
 ()
 line_count = get_line_count(file_name)
 print('===%s=== line count total: %d' % (file_name, line_count))
 line_count = line_count - line_num +1
 print('===%s=== line %d to end' % (file_name, line_count))
 
 
 for i in range(line_num):
  last_line = (file_name, line_count) # Read from line_count.
  print('line[%d]:%s' % (line_count, last_line), end='')
  line_count += 1
 
 
 
try:
 opts, args = ([1:], "hvn:t:", ["help", "output=", "numline=", "tail=", "version"])
except :
  print("argv error,please input")
 
for cmd, arg in opts:
 if cmd in ("-h", "--help"):
 print("usage:  -n number filename \nor  -t number filename")
 ()
 elif cmd in ("-n", "--numline"): # Print the line_num line at the beginning of the file
 line_num=int(arg)
 file_names=args[:]
 read_head_line(file_names, line_num)
 elif cmd in ("-t", "--tail"): # Print the line_num line at the end of the file
 line_num=int(arg)
 file_names=args[:]
 read_last_line(file_names, line_num)
 
 elif cmd in ("-v", "--version"):
 print("%s %s" % ([0], VERSION))
 
()

The above tutorial on how to print the first few lines or the last few lines of a file in python is all I have to share with you.