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’
>Solution :
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 are cannot be integers. But it’s not good practise to use input as variable name. Never use built-in function names like that.