简体   繁体   中英

Reading specific lines from a file and writing to another file in python

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"
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: ... )

There are two problems in your code:

  1. What ever you are writing in the file 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 ie the start of the file.
  2. The second issue is similar but on the other 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM