DDR爱好者之家 Design By 杰米

写一个类似linux head的小工具,在window下用。

head.py 

# -*- 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 = file.read(8192 * 1024 )
 if not buffer:
  break
 line_count += buffer.count('\n')
 file.close()
 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(f.readline(), end='')
 
 
 
def read_last_line(flist, line_num):
 
 for file_name in flist:
 
 linecache.clearcache()
 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 = linecache.getline(file_name, line_count) #从第line_count行读起
  print('line[%d]:%s' % (line_count, last_line), end='')
  line_count += 1
 
 
 
try:
 opts, args = getopt.getopt(sys.argv[1:], "hvn:t:", ["help", "output=", "numline=", "tail=", "version"])
except getopt.GetoptError:
  print("argv error,please input")
 
for cmd, arg in opts:
 if cmd in ("-h", "--help"):
 print("usage: head.py -n number filename \nor head.py -t number filename")
 sys.exit()
 elif cmd in ("-n", "--numline"): #打印文件开头的line_num行
 line_num=int(arg)
 file_names=args[:]
 read_head_line(file_names, line_num)
 elif cmd in ("-t", "--tail"): #打印文件结尾的line_num行
 line_num=int(arg)
 file_names=args[:]
 read_last_line(file_names, line_num)
 
 elif cmd in ("-v", "--version"):
 print("%s %s" % (sys.argv[0], VERSION))
 
sys.exit()

以上这篇python打印文件的前几行或最后几行教程就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

DDR爱好者之家 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
DDR爱好者之家 Design By 杰米