您好,登錄后才能下訂單哦!
python中怎么打印文件的前幾行,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
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 linecacheVERSION="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_countdef 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 += 1try: 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()
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。