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(' ','')) print('文件' + fname + '最后一行为:' + last_line.replace(' ',''))