当前位置:首页 » python教程 » 正文

python打印文件的前几行或最后几行教程

看: 1427次  时间:2020-08-17  分类 : python教程

写一个类似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打印文件的前几行或最后几行教程就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!