如何用python读取文本中指定行的内容

如题所述

1 利用python的readlines()函数:

[python] view plain copy
<strong><span style="font-size:24px;"> </span><span style="font-size:14px;">fobj = open(r'Ori.Data.txt','r')
for line in fobj.readlines()[1000:]
fobj.close()</span></strong>

2 利用 linecache

[python] view plain copy
<strong><span style="font-size:14px;"> import linecache
print(linecache.getline(r'D:\z.txt',10))</span></strong>

3 读取10行到13行中的内容

[python] view plain copy
<span style="font-size:14px;"> <strong> lnum = 0
with open('pit.txt', 'r') as fd:
for line in fd:
lnum += 1;
if (lnum >= 10) && (lnum <= 13):
print line
fd.close()</strong></span>

4 求文本的行数

[python] view plain copy
<span style="font-size:14px;"><strong> fobj = open('Ori_Data.txt','r')
row_len = len(fobj.readlines()) </strong></span>
[python] view plain copy
<span style="font-size:14px;"><strong>
</strong></span>
[python] view plain copy
<span style="font-size:14px;"><strong> fobj = open(filepath,'r')
data = fobj.read()
fobj.close()
text_len = data.count('\n')<span style="font-family: Arial, Helvetica, sans-serif;"></span></strong></span>
温馨提示:答案为网友推荐,仅供参考
相似回答