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?

Dani AI

Generated

The error you hit is the classic type-mismatch from calling file.write() with an integer. In plain terms: the file write() method expects text (a string), not a numeric type, so write(num) raises TypeError: write() argument must be str, not int. Converting the number to a string and adding a newline before writing fixes that. was on the right track; correctly highlighted stripping and skipping blank lines; and ’s suggestion to write odds in the same pass is the most efficient approach.

A robust, production-friendly workflow:

  • Open files with context managers (the with statement) so they always close.
  • Iterate the input file line-by-line (streaming) to avoid loading everything into memory.
  • Use line.strip() and skip empty lines to avoid conversion errors from stray whitespace.
  • Convert with a try/except catching ValueError so malformed lines don’t crash the run.
  • Test parity and write the textual representation plus a newline to the appropriate output file. Zero is even; negative integers work with the same parity test.

Practical notes and gotchas:

  • Don’t open output files inside the per-line loop; open them once and reuse the handles.
  • For very large inputs prefer writing as you go rather than building big lists and joining at the end.
  • If running this code years later, be aware of Python 2 vs Python 3 differences (for example raw_input -> input, print syntax). The write() behavior (accepting only strings) is the same in both.
  • If non-ASCII characters are present, specify an encoding when opening files in Python 3 to avoid decoding issues.

Troubleshooting checklist: confirm the exact TypeError, ensure you convert numbers to strings and append a newline, handle blank/malformed lines with try/except, and use with open(...) so files get closed automatically. This addresses the immediate error and makes the script safer and more maintainable.

Recommended Answers

All 3 Replies

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.