小編給大家分享一下python如何打印文件的前幾行或最后幾行,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
從策劃到設計制作,每一步都追求做到細膩,制作可持續(xù)發(fā)展的企業(yè)網(wǎng)站。為客戶提供網(wǎng)站設計、做網(wǎng)站、網(wǎng)站策劃、網(wǎng)頁設計、主機域名、虛擬主機、網(wǎng)絡營銷、VI設計、 網(wǎng)站改版、漏洞修補等服務。為客戶提供更好的一站式互聯(lián)網(wǎng)解決方案,以客戶的口碑塑造優(yōu)易品牌,攜手廣大客戶,共同發(fā)展進步。寫一個類似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"): #打印文件結(jié)尾的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如何打印文件的前幾行或最后幾行”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!