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 check if file is empty or contains anything except an integer?

I want to open a file and check if in that file is an integer and if not write a 0.

I know how to write into a file and read a file, but to check if there is an integer and or there is something else, so I can replace it.

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

>Solution :

Alternative using .isdigit method of strings. It also tolerates new line \n at the end of the file by stripping it out.

with open("file","r") as fd:
    string = fd.read()
    if not string.strip().isdigit():
        with open("file","w") as fd:
            fd.write("0")
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