牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2015-01-14 投稿人: 浏览次数:13778

1 利用python的readlines()函数:   

<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

<strong><span style="font-size:14px;">   import linecache
   print(linecache.getline(r"D:z.txt",10))</span></strong>

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

 <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 求文本的行数

 
<span style="font-size:14px;"><strong>    fobj = open("Ori_Data.txt","r")
    row_len = len(fobj.readlines())  </strong></span>
<span style="font-size:14px;"><strong>
</strong></span>
<span style="font-size:14px;"><strong>     fobj = open(filepath,"r")
     data = fobj.read()
     fobj.close()
     text_len = data.count("
")<span style="font-family: Arial, Helvetica, sans-serif;"></span></strong></span>

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。