怎么通过Python获取文件指定行的内容?

Python (226) 2023-07-27 06:07:15

linecache, 可以用它方便地获取某一文件某一行的内容。而且它也被 traceback 模块用来获取相关源码信息来展示。

用法很简单:

>>>importlinecache
>>>linecache.getline('/etc/passwd',4)
'sys:x:3:3:sys:/dev:/bin/sh\n'

linecache.getline 第一参数是文件名,第二个参数是行编号。如果文件名不能直接找到的话,会从 sys.path 里找。

如果请求的行数超过文件行数,函数不会报错,而是返回''空字符串。

如果文件不存在,函数也不会报错,也返回''空字符串。

#Python的标准库linecache模块非常适合这个任务
importlinecache
the_line=linecache.getline('d:/FreakOut.cpp',222)
print(the_line)
#linecache读取并缓存文件中所有的文本,
#若文件很大,而只读一行,则效率低下。
#可显示使用循环,注意enumerate从0开始计数,而line_number从1开始
defgetline(the_file_path,line_number):
ifline_number<1:
return''
forcur_line_number,lineinenumerate(open(the_file_path,'rU')):
ifcur_line_number==line_number-1:
returnline
return''
the_line=linecache.getline('d:/FreakOut.cpp',222)
print(the_line)
THE END

发表回复