扫码关注官方订阅号
如题,一个文件file里面有若干行,用python 怎样实现 打开文件 只读取倒数20行并打印出来?
认证高级PHP讲师
原始版本(没有关闭文件,因为是在手机上敲的):
print('\n'.join(open('filename','r').readlines()[-20:]))
省内存的逐行读入:
lines = [] with open("filename", "r") as f: while True: tlines = f.readlines(100) if not tlines: break tlineslen = len(tlines) if tlineslen <= 20: lines = lines[tlineslen - 20:] + tlines break lines = tlines[-20:] print(lines)
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
原始版本(没有关闭文件,因为是在手机上敲的):
省内存的逐行读入: