Moving contents from one file to a new one in python

Viewed 33

i want to print in the even file all even numbers with spaces between them eg: 12 6 20 10 not 1262010 with no spaces in front or back. How can i do this?

def write_positive_even_to_file(filename):
    with open(filename, 'r') as orginal, open('xxx.txt', 'a') as even:
        red = orginal.read().split()
        for number in red:
            if number % 2 == 0:
                even.write(number + " ") 

Input file:

15 12 6
7 20 9 10
13 17
3
1 Answers

You need to split each input line into tokens (assumed to represent integers) convert to int then determine if any value is even.

Something like this:

def write_positives(infile, outfile, mode='a'):
    with open(infile) as fin, open(outfile, mode) as fout:
        if (evens := [x for x in map(int, fin.read().split()) if x % 2 == 0]):
            print(*evens, file=fout)

By printing the unpacked list you will, by default, have space separation

Related