如何读取python中第7行到第265行的行?

时间:2016-02-02 15:19:00

标签: python python-2.7

我正在读一个.txt文件,但我想读取第6行到第265行的文件。有人可以告诉我该怎么做吗? Output.txt:

my code:

    h = httplib.HTTPSConnection(host, port)

h.set_debuglevel(1)

headers = {

    "Content-Type": "multipart/form-data; boundary=%s" % (boundary,),

    "Connection": "Keep-Alive",

}

h.request('POST', uri, body, headers)

res = h.getresponse()
filehandle = open("Output.txt", "wb")
filehandle.write(res.read())
import itertools
with open("Output.txt", "rb") as infile, open("output1.txt", "wb") as outfile:
    for line in itertools.islice(infile, 6, 265):
        outfile.write(line)
filehandle.close()

上面的代码只是阅读第6行但是如何从第6行读到第265行?

3 个答案:

答案 0 :(得分:4)

我建议使用islice包中的itertools

import itertools

 with open("input.txt", "rb") as infile, open("output.txt", "wb") as outfile:
     for line in itertools.islice(infile, 6, 265):
         outfile.write(line)

响应您的评论请求将前6个和后12个读入文件,其余文件读入另一个文件,我将执行以下操作

from collections import deque
from itertools import islice 

with open("input.txt", "rb") as infile, open("output1.txt", "wb") as outfile1, open("output2.txt", "rb") as outfile2:
    outfile.write(''.join(islice(infile, 6)))

    q = deque(islice(infile, 12))
    outfile2.write(''.join(q))

    for line in infile:
        q.append(line)
        outfile2.write(q.popleft())

    outfile.write(''.join(q))

这里的想法是

  1. 将前6行写入第一个文件
  2. 将接下来的12行写入第二个文件并使用它们填充队列
  3. 将新行推入队列并关闭旧行,直到输入文件耗尽
  4. 将队列中剩余的12行(最后12行)写入第一个输出文件。

答案 1 :(得分:2)

这是一个例子。它打印第6行,直到第265行。

with open("file", "rb") as fp:
    for linenr, line in enumerate(fp):
        if linenr > 264:
            break
        elif linenr >= 5:
            print(line)

请注意,第6行为linenr == 5,第265行为264

您可以使用以下示例将选定的行保存到另一个文件。

with open("fileoutput", "wb") as outputfile, open("fileinput", "rb") as inputfile:
    for linenr, line in enumerate(inputfile):
        if linenr > 264:
            break
        elif linenr >= 5:
            outputfile.write(line)

答案 2 :(得分:0)

正如你在其中一条评论中提到的那样,你想要阅读文件的前4行和决赛12行,你可以使用@DavisYoshida的答案到第一部分,这到最后部分

from collections import deque

def tail(iterable,n=None):
    """Return an iterator over the last n items, if n is none return a iterator over all elemens
       in iterable save the first

       tail('ABCDEFG',3) --> E F G
       tail('ABCDEFG')   --> B C D E F G """
    if n is None:
        resul = iter(iterable)
        next(resul,None)
        return resul
    return iter(deque(iterable, maxlen=n))

这是来自recipe文档的itertools,稍作修改

例如

>>> with open("Output.txt","rb") as infile:
        for i,line in enumerate(islice(infile,0,4),1):
            print(i,"-->",line)
        print()
        for i,line in enumerate(tail(infile,12)):
            print(-(12-i),"-->",line)

1 --> b'----Nuance_NMSP_vutc5w1XobDdefsYG3wq\n'
2 --> b'Content-Disposition: form-data; name="Audio"; paramName="TEXT_TO_READ"\n'
3 --> b'Content-Type: audio/x-wav;codec=pcm;bit=16;rate=8000\n'
4 --> b'Nuance-Context: f886d51f-84f7-491e-9412-1d1f4e33304e\n'

-12 --> b'Content-Disposition: form-data; name="Audio"; paramName="TEXT_TO_READ"\n'
-11 --> b'Content-Type: audio/x-wav;codec=pcm;bit=16;rate=8000\n'
-10 --> b'Nuance-Context: f886d51f-84f7-491e-9412-1d1f4e33304e\n'
-9 --> b'\n'
-8 --> b'\n'
-7 --> b'----Nuance_NMSP_vutc5w1XobDdefsYG3wq\n'
-6 --> b'Content-Disposition: form-data; name="QueryResult"\n'
-5 --> b'Content-Type: application/JSON; charset=utf-8\n'
-4 --> b'Nuance-Context: f886d51f-84f7-491e-9412-1d1f4e33304e\n'
-3 --> b'\n'
-2 --> b'{"TTSStatus":"Success","result_type":"NVC_TTS_CMD","NMAS_PRFX_SESSION_ID":"28fdbb23-a278-4e7d-8275-a046071823b3","NMAS_PRFX_TRANSACTION_ID":"1"}\n'
-1 --> b'----Nuance_NMSP_vutc5w1XobDdefsYG3wq--'
>>>