How to check if file is empty or contains anything except an integer?

Question:

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.

Asked By: Bozhidar Botev

||

Answers:

This is a bit ugly, but it works, first you open the file for read, and try to convert to int. If it works, all is ok else you close the file and open it again for writing and write 0.

with open("file","r") as fd:
    try: 
        print(int(fd.read()))
    except:
        fd.close()
        with open("file","w") as fd:
            fd.write("0")
Answered By: Mauxricio

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")
Answered By: LucG
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.