0

I have been trying to obtain certain lines of an input file, so I used the file "inputfile" for obtaining just the even lines.

f= open('inputfile.txt', 'r')
for i,line in enumerate(f):
     if i%2==0:
         print line

This way I obtain the lines printed, but, however, I do not know how to send these resulting lines to an output file, because when I initially tried to do it, I just obtained the first line. What can I do?

1
  • 2
    What did you do when you initially tried? Can you show us? Commented Oct 24, 2013 at 22:02

3 Answers 3

3

The most efficient way to get just the even lines is to use itertools.islice() and select only every 2nd item:

from itertools import islice

with open('inputfile.txt', 'r') as infile, open('outputfile.txt', 'w') as outfile:
    outfile.writelines(islice(infile, 0, None, 2))

Using your method works just fine too, provided you write the line in the loop:

with open('inputfile.txt', 'r') as infile, open('outputfile.txt', 'w') as outfile:
    for i, line in enumerate(f):
        if i % 2 == 0:
            outfile.write(line)
Sign up to request clarification or add additional context in comments.

Comments

0

Your method works great, congratulations. If you want to write the result to another file, you can do it with the same way you read it, only slightly different.

input_file = ('inputfile.txt', 'w')
output_file = ('outputfile.txt', 'w')
for i,line in enumerate(input_file):
     if i%2==0:
         output_file.write(line)  

Also, so you don't forget to close the file at the end of your program, it is recommended to use the with statement, as martijn showed

with open('inputfile.txt', 'r') as input_file, open('outputfile.txt', 'w') as output_file:

Comments

0

I think that Martijn/alKid's answers are what you should go with, but just for the sake of completeness, I'll add that you could run your script as is, printing the lines to standard out (ie. the console, in this case), and just redirect the output to a file: python my_script.py > output.txt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.