Python script to split a text file by even or odd numbers

June 20, 2008 at 11:50 am (opensource, software, tips) (, , , , , , )

written a short script to split a file into even or odd line numbers 🙂

#!/usr/bin/python
## loop do something to each line of input file
## changed to write the even line numbers to a file
## and the odd line numbers to another
## note that even numbers start with line 0 (not 1!)
## usage: sort-even-odd.py inputfile
##  written by kevinl @ kevinl.wordpress.com

import sys

def isodd(n):
    return bool(n%2)

input=open(sys.argv[1], 'r')
L=input.readlines()
evenout=open('evenout', 'w')
oddout=open('oddout','w')

for linecount in range(len(L)):
    if isodd(linecount):
        oddout.write(L[linecount])
    else:
        evenout.write(L[linecount])
    #print "line number is " + str(linecount)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: