Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read and write into another text file having numbers, strings and special characters

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading