1

I am reading a .txt file but I want to read the file from line number 6 till line number 265. can some tell me how to do that ? 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()

the above code is just reading line 6 but how to read from line 6 to line 265 ?

sam
  • 203
  • 4
  • 17

3 Answers3

4

I recommend using islice from the itertools package.

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)

In response to your comment requesting to read the first 6 and last 12 into a file, and the rest into another file, I would do something like the following

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))

The idea here is to

  1. Write the first 6 lines to the first file
  2. Write the next 12 lines to the second file and populate a queue with them
  3. Push new lines onto the queue and pop old lines off until the input file is exhausted
  4. Write the 12 lines remaining in the queue (the last 12 lines) to the first output file.
Davis Yoshida
  • 1,757
  • 1
  • 10
  • 24
  • it is reading till end of file. it is not stopping at line 265. – sam Feb 02 '16 at 15:47
  • If you reply with the code you are using I can tell you what you are doing wrong. – Davis Yoshida Feb 02 '16 at 20:44
  • you can see my code above. I need your help badly. Please help . else please answer this question - http://stackoverflow.com/questions/35159846/how-to-remove-the-first-four-lines-and-the-last-12-lines-in-to-a-file-in-python?noredirect=1#comment58041322_35159846 – sam Feb 02 '16 at 21:07
  • you can see my Outputfile.txt. I uploaded here. – sam Feb 02 '16 at 21:12
  • I want to read the first four lines and the last 12 lines in to a file. remaining binary data into a another file. please help. – sam Feb 02 '16 at 21:14
  • This appears to have just 173 lines in it, which means your input probably doesn't have 265 lines to begin with. – Davis Yoshida Feb 02 '16 at 21:58
  • can you please help me ? I want to read the first four lines and the last 12 lines in to a file. remaining binary data into a another file. – sam Feb 02 '16 at 22:01
  • I've edited my response to contain code that does this. Let me know if it works for you. – Davis Yoshida Feb 03 '16 at 03:57
  • thanks. but what about the binary - where you reading and where is it getting stored ? – sam Feb 03 '16 at 08:52
  • It's going into outfile2 – Davis Yoshida Feb 03 '16 at 14:19
2

Here is an example. It prints line number 6 till line number 265.

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

Please note that linenr == 5 for the 6th line and 264 for the 265th line.


You can use following example to save the selected lines to another file.

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)
wewa
  • 1,628
  • 1
  • 16
  • 35
  • how to save the data from line number 6 to line number 264 in a .txt file ? – sam Feb 02 '16 at 15:25
  • @sam added another example. – wewa Feb 02 '16 at 15:30
  • it is reading all the lines from line number 7 till end of file. it is not stopping at line 263 – sam Feb 02 '16 at 15:42
  • Sorry now, I corrected it, now it starts from line number 6 and ends at line number 265. – wewa Feb 02 '16 at 16:40
  • its the same problem. printing till the end of file – sam Feb 02 '16 at 17:26
  • Sorry again, now it should work. I messed up with the if statements. – wewa Feb 02 '16 at 18:14
  • no !! same problem !! can you please answer this question http://stackoverflow.com/questions/35159846/how-to-remove-the-first-four-lines-and-the-last-12-lines-in-to-a-file-in-python?noredirect=1#comment58039361_35159846 – sam Feb 02 '16 at 18:20
  • 1
    you can also give the inicial number to enumerate as `enumerate(iterable,1)` if you don't want it to start in 0 – Copperfield Feb 02 '16 at 23:11
  • 1
    I tested my posted code and it works (of course you have to replace `fileoutput` and `fileinput` with the paths to your output and input files). And I found the reason why also the corrected code reads your file till the end. Your posted input file only has 211 lines and you asked for reading from line 6 till 265. Therefore you read till the end of your input file. – wewa Feb 03 '16 at 06:35
0

as you mentions in one of yours comments that you want to read the first 4 lines and the finals 12 lines of the file, you can use the answer of @DavisYoshida to the first part and this to the final part

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))

this a recipe from the documentation of itertools with a little changes

for example

>>> 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--'
>>>         
Copperfield
  • 8,131
  • 3
  • 23
  • 29