Trey
Trey

Reputation: 73

How to write every other line in a text file?

inputFile = open('original_text.txt','r')
outputFile = open('half_text.txt','w')

line = inputFile.readline()
count = 0 
for line in inputFile:
    outputFile.write(line)
    count += 1
    if count % 2 == 0:
        print(line)

inputFile.close()
outputFile.close()

It keeps skipping the 1st line. For instance, the text file right now has 10 lines. So it prints the 3rd 5th 7th and 9th. So I'm just missing the first.

Upvotes: 1

Views: 3584

Answers (3)

Sha2b
Sha2b

Reputation: 457

The for loop will go over the file line by line and when you use the readline, it will advance the pointer forward inside the loop. Therefore odd will go over odd numbered lines and even goes over even numbered lines.

with open (path, 'r') as fi:
    for odd in fi:
        even = fi.readline()
        print ('this line is odd! :' + odd)
        print ('this line is even! :' + even)

Upvotes: 0

Hooting
Hooting

Reputation: 1711

use next to skip the next line. You may need to watch for a StopIteration error on the call to next(fh) if you have odd lines.

outputFile = open('half_text.txt','w')

with open('original_text.txt') as fh:
    for line1 in fh:
        outputFile.write(line1)
        try:
            next(fh)
        except StopIteration:
            pass

outputFile.close()

Upvotes: 3

Prune
Prune

Reputation: 77847

This skips the first line because you read it and throw it away before the loop. Delete line 4,

line = inputFile.readline()

Add change the count parity to odd with

if count % 2 == 1:

For a slightly better design, use a boolean that toggles:

count = False
for line in inputFile:
    outputFile.write(line)
    count = not count
    if count:
        print(line)

inputFile.close()
outputFile.close()

I tried running the program on itself:

inputFile = open('this_file.py', 'r')

count = False

    outputFile.write(line)

    if count:



outputFile.close()

Upvotes: 2

Related Questions