小编给大家分享一下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如何打印文件的前几行或最后几行”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。