甲方用的windows服务器,不方便安装其他软件,日志文件太大了需要分割,就写了个python脚本读取最后若干行并输出或存为文件。
直接复制粘贴保存即可使用,使用方法见代码内的注释。
# -*- coding: utf-8 -*-
import sys
import os
import string
"""
读取文本文件中的倒数n行,调用格式为:python 本文件 要读取的文本文件名 要读取的行数
比如读物a.txt的最后10行,传参为python get_text_file_last_n_content.py a.txt 10
"""
def get_input_params(params_index=1):
"""
获取输入的命令行参数
"""
import sys
param_text = sys.argv[params_index]
print(f'参数内容:{param_text}')
return param_text
# file_path_full = r"api1-stdout.2022-02-08.log" # 要读取的文件名
# read_line_count = 10 # 要读取的行数
file_path_full = get_input_params(1)
read_line_count = int(get_input_params(2))
def get_now_time_str(format_str = '%Y-%m-%d %H:%M:%S'):
"""
获取当前时间/获取北京时间(字符串 %Y-%m-%d %H:%M:%S 格式)
"""
from datetime import datetime, timedelta, timezone
return datetime.utcnow().replace(tzinfo=timezone.utc).astimezone(timezone(timedelta(hours=8))).strftime(format_str)
def write_2_file(file_name, content):
"""
覆盖式将内容写入文件,如果文件不存在则创建文件
"""
try:
f = open(file_name, 'w')
print(f'{file_name} 文件打开成功')
content = f.write(content)
f.close()
except IOError:
print(f'{file_name} 文件打开错误')
def get_last_n_lines(file_path_full, n):
blk_size_max = 4096
n_lines = []
with open(file_path_full, 'rb') as fp:
fp.seek(0, os.SEEK_END)
cur_pos = fp.tell()
while cur_pos > 0 and len(n_lines) < n:
blk_size = min(blk_size_max, cur_pos)
fp.seek(cur_pos - blk_size, os.SEEK_SET)
blk_data = fp.read(blk_size)
assert len(blk_data) == blk_size
str_data = blk_data.decode("gbk")
lines = str_data.split('\n')
# adjust cur_pos
if len(lines) > 1 and len(lines[0]) > 0:
n_lines[0:0] = lines[1:]
cur_pos -= (blk_size - len(lines[0]))
else:
n_lines[0:0] = lines
cur_pos -= blk_size
fp.seek(cur_pos, os.SEEK_SET)
if len(n_lines) > 0 and len(n_lines[-1]) == 0:
del n_lines[-1]
return n_lines[-n:]
def print_content(content_list):
for i in content_list:
print(f"{i}")
def save_content_2_new_file(new_file_name,content_list):
write_2_file(new_file_name,"\n".join(content_list))
if __name__ == '__main__':
now_time_str = get_now_time_str('%Y%m%d_%H%M%S')
content_list = get_last_n_lines(file_path_full, read_line_count)
# print_content(content_list)
save_content_2_new_file(f"{file_path_full}{now_time_str}",content_list)
Q.E.D.