Python读取文件首行和尾行

fname = 'test.sh2'
with open(fname, 'r', encoding='utf-8') as f:  # 打开文件
    lines = f.readlines()  # 读取所有行
    first_line = lines[0]  # 取第一行
    last_line = lines[-1]  # 取最后一行
    print('文件' + fname + '第一行为:'+ first_line.replace('\n',''))
    print('文件' + fname + '最后一行为:' + last_line.replace('\n',''))

  

posted @ 2021-06-23 15:20  lucky_tomato  阅读(432)  评论(0编辑  收藏  举报