-4

I have a text file with the below numbers, strings and special characters.

63
148
77
358765
Orange
44.7
14
%
61
80
**

How to read the file and write into another file with only odd numbers.

Here's my rough code

with open("Odd-Numbers.txt", "r") as i:

with open("Output.txt", "w") as o:

    odds = []

            for num in i:
        try:
            num = int(num)
            if num % 2:
                odds.append(num)
        except ValueError:
            pass

    for line in i:
        output.write(line)
        print(line, end = "")

It is giving me the error: invalid literal for int() with base 10: 'Mango\n'

Karyala
  • 13
  • 6
  • 1
    Please fix the indentation issues. Also, `input` is not the best choice of variable name, because it is a built-in. I would suggest you change that as well. – BrokenBenchmark Jan 24 '22 at 08:15

1 Answers1

0

If you use int(num) you have to make sure, that num is always a number, otherwise string as 'Mango' will give you the ValueError.

For now, you can try this:

with open("Odd-Numbers.txt", "r") as input_file:

    with open("Output.txt", "w") as output_file:

        odds = []

        for num in input_file:
            try:
                num = int(num)
                if num % 2:
                    odds.append(num)
            except ValueError:
                pass

        for line in odds:
            output_file.write(str(line) + '\n')
        

That code will ignore any values, that cannot be integers. But it's not good practise to use input as variable name. Never use built-in function names like that.

NixonSparrow
  • 6,130
  • 1
  • 6
  • 18