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

Python09

如何用python读取文本中指定行的内容,第1张

1.默认你知道“指定行”的行号

那么:

def appoint_line(num,file):

    with open(file,"r",encoding='utf-8') as f:

        out = f.readlines[num-1]

        return out

print(appoint_line(2,"c:/text.txt"))

以上示例为读取c盘下的text.txt文件的第二行

2.假如所谓“指定行”为开头几个字符,这里假设为三个

def appoint_line(file):

    # appoimt_spring是指你指定行的前三个字符,你可以自行指定

    appoint_spring = input(">>").strip()

    with open(file,"r",encoding='utf-8') as f:

       for line in f.readlines():

            if line[0:3] == appoint_spring:

                return line

print(appoint_line("c:/text.txt"))

以上示例为根据你输入的所指定行的前三个字符打印出c盘下的text.txt文件下的“指定行”

1.全部读到成列表然后选取行(容易超时,乱码等问题)

2.利用迭代工具,代码如下:

from itertools import islice

with open('data.tsv', 'r') as f:

for line in islice(f, 1, None):

# process data

f.close()

修改islice函数中第2个参数n即可,表示读到f文件对象的第n行

#!/usr/bin/env python

# coding: utf-8

def getfilelines(filename, eol='\n', buffsize=4096):

    """计算给定文件有多少行"""

    with open(filename, 'rb') as handle:

        linenum = 0

        buffer = handle.read(buffsize)

        while buffer:

            linenum += buffer.count(eol)

            buffer = handle.read(buffsize)

        return linenum

def readtline(filename, lineno, eol="\n", buffsize=4096):

    """读取文件的指定行"""

    with open(filename, 'rb') as handle:

        readedlines = 0

        buffer = handle.read(buffsize)

        while buffer:

            thisblock = buffer.count(eol)

            if readedlines < lineno < readedlines + thisblock:

                # inthisblock: findthe line content, and return it

                return buffer.split(eol)[lineno - readedlines - 1]

            elif lineno == readedlines + thisblock:

                # need continue read line rest part

                part0 = buffer.split(eol)[-1]

                buffer = handle.read(buffsize)

                part1 = buffer.split(eol)[0]

                return part0 + part1

            readedlines += thisblock

            buffer = handle.read(buffsize)

        else:

            raise IndexError

def getrandomline(filename):

    """读取文件的任意一行"""

    import random

    return readtline(

        filename,

        random.randint(0, getfilelines(filename)),

        )

if __name__ == "__main__":

    import sys

    import os

    if len(sys.argv) == 1:

        print getrandomline("/home/tim/documents/users.csv")

    else:

        for f in filter(os.path.isfile, sys.argv[1:]):

            print getrandomline(f)

对于超大文件建议用逐行或分块的方式处理;逐行处理可能慢一些,但编码更简单清晰一点;上面给出的是按分块方式处理的。