only1smokey
only1smokey

Reputation: 31

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.

Upvotes: 0

Views: 61

Answers (2)

Mauxricio
Mauxricio

Reputation: 190

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")

Upvotes: 2

LucG
LucG

Reputation: 1334

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")

Upvotes: 2

Related Questions