Python3实现从文件中读取指定行的方法
作者:皮蛋 时间:2021-01-06 04:18:17
本文实例讲述了Python3实现从文件中读取指定行的方法。分享给大家供大家参考。具体实现方法如下:
# Python的标准库linecache模块非常适合这个任务
import linecache
the_line = linecache.getline('d:/FreakOut.cpp', 222)
print (the_line)
# linecache读取并缓存文件中所有的文本,
# 若文件很大,而只读一行,则效率低下。
# 可显示使用循环, 注意enumerate从0开始计数,而line_number从1开始
def getline(the_file_path, line_number):
if line_number < 1:
return ''
for cur_line_number, line in enumerate(open(the_file_path, 'rU')):
if cur_line_number == line_number-1:
return line
return ''
the_line = linecache.getline('d:/FreakOut.cpp', 222)
print (the_line)
希望本文所述对大家的Python程序设计有所帮助。
标签:Python,文件,读取
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
PHP手机号码归属地查询代码(API接口/mysql)
2023-10-26 04:35:44
好的产品设计并非始于图片,而是对人的理解
2009-08-02 20:25:00
怎样设置密码保护问题
2009-02-16 13:12:00
![](https://img.aspxhome.com/file/UploadPic/20092/16/3270103042_b5979f4ce4_o-64s.png)
Go Gin实现文件上传下载的示例代码
2023-06-21 15:11:13
SQL SERVER 建立索引
2010-07-02 21:01:00
为自己的网站添加RSS功能
2007-11-05 19:18:00
![](https://img.aspxhome.com/file/UploadPic/20072/20072311555566s.jpg)
带你深入了解MySQL语句优化的基本原则
2008-11-27 17:00:00
将SQL Server中所有表的列信息显示出来
2009-01-08 16:27:00
Python基于jieba分词实现snownlp情感分析
2023-11-14 21:43:38
![](https://img.aspxhome.com/file/2023/0/63590_0s.jpg)
Python操作sqlite3快速、安全插入数据(防注入)的实例
2022-04-22 16:38:14
Python判断文件和文件夹是否存在的方法
2023-09-12 17:22:00
asp 静态页面的另一种思路
2011-04-08 10:32:00
挑战! 纯Javascript 重现经典网游! <魔力宝贝>
2008-10-04 10:37:00
![](https://img.aspxhome.com/file/UploadPic/200810/4/2008104104524850s.jpg)
ASP 正则表达式常用的几种方法(execute、test、replace)
2010-03-02 20:23:00
用SQL Server事件探查器创建跟踪
2009-02-24 17:45:00
python 百度aip实现文字识别的实现示例
2023-12-15 19:53:47
![](https://img.aspxhome.com/file/2023/5/66805_0s.png)
网马解密大讲堂——网马解密中级篇(Eval篇)
2009-09-16 16:04:00
Python素数检测实例分析
2021-05-22 02:11:41
一个ASP写的侧边菜单栏
2010-05-27 12:22:00
ASP Session对象的集合以及属性方法事件
2009-02-02 09:26:00