Reputation: 15
I have a file containing 1000 lines. First 15 lines will be header information.
I am trying to do the below :-
1) Read the file 2)Get the number of lines with header information. It will return 15 3)write lines 1-15 to a text file.
I am able to do 1 and 2 correctly, but not the 3rd step. Any inputs please?
Below is my code
#!/usr/bin/python
import numpy;
import os;
import math;
import cPickle; import time
from numpy import arange, sign
import copy
import re
import sys
import string
import mmap
head_lines = 0;
count=1
fide = open("text1.txt","r");
while (count==1): #We skip header
head_lines = head_lines+1;
line = fide.readline();
if 'END OF HEADER' in line:
print 'End of the Header reached'
break
print "hello world"
print head_lines
nlines = head_lines;
key=1;
while (key < nlines):
file1 = open("Header.txt","w")
lines = fide.readline()
file1.write(lines)
key = key+1;
print "done"
Upvotes: 0
Views: 429
Reputation: 114098
with open("input.txt") as f1:
with open("output.txt","w") as f2:
for _ in range(15):
f2.write(f1.readline())
is that what you are asking for?
(in python2.7 I think you can do with open('f1') as f1,open('f2','w') as f2: ...
)
Upvotes: 1
Reputation: 3026
There are two problems in your code:
header.txt
you'll be overwriting it every time you loop on the second while
because you are re-opening the file which will put the file pointer to its origin i.e. the start of the file.fide
. You open it putting the file pointer to the start of the file and read one line until the end of the headers. And in the second while
loop you keep reading lines from the same file pointer fide
so you're reading the next nlines
.You could store the header's lines in a list and then write those strings in the output file.
Upvotes: 0