I am trying to make a program that reads from a "integers.txt" file which contains:
1
2
3
4
11
13
15
16
18
20
33
39
42
48
50
51

and finds all the even numbers in "integers.txt" and writes them to a new file "evens.txt"
then finds all the odd numbers in "integers.txt" and does the same.

So far I have:

#sieve

import sys

def open_read(file_name, mode):
    try:
        the_file = open(file_name, mode)
    except(IOError):
        print "Unable to open file", file_name
        sys.exit()
    else:
        return the_file


def write_evens():
    
    even_file = open("evens.txt", "w")
    the_file = open_read("integers.txt", "r")

    for num in the_file:
        num = int(num)
        if num % 2 == 0:
            even_file.write(num)


def main():
    

    write_evens()



main()

raw_input("\n\nPress enter to exit.")

I can't figure out what this error that it creates means, or how to get around it. Maybe I am approaching the program wrong....any ideas?

you have to convert the num variable to a string
like such:
even_file.write('%s\n'%num)

Also, you could write a better line processing. In the loop for num in the_file , num is a string like '51\n' . A good way to handle this is

for num in the_file:
        num = num.strip() # get rid of white space around the line's content (the \n)
        if not num:
            continue # skip blank lines (the last line could be blank)
        num = int(num)
        if num % 2 == 0:
            even_file.write(str(num))

Also, write to the odd numbers file at the same time. Plus, do you want to test for zero or negative integers?

def write_evens():
 
    even_file = open("evens.txt", "w")
    odds_file = open("odds.txt", "w")

    the_file = open_read("integers.txt", "r")
 
    for rec in the_file:
        rec = rec.strip()
        try :
            num = int(rec)
            if num % 2 == 0:
                output_fp = even_file
            else:
                output_fp = odds_file

            output_fp.write( ("%d\n" % (num) )

        ## conversion to an integer failed
        except:
            print rec, "is not a valid integer"

    even_file.close()
    odds_file.close()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.