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

时间:2021-05-22

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章