user5670271
user5670271

Reputation: 3

How can I check that a text file has at least 1 character

I have a text file how can I check in python that the text file has at least 1 number or alphabetic character and not just white spaces.

Upvotes: 0

Views: 258

Answers (1)

Mark Skelton
Mark Skelton

Reputation: 3891

Here is what I did. I read the file putting the data into the string data. Then I used data.strip() to remove the leading and trailing whitespace. Then I checked to see if there is anything left from data.strip(). If there is you have characters in the file, if not your file has only whitespace or is completely empty.

with open("filename.txt", "r") as file:
    data = file.read()

if data.strip():
    print("empty")
else:
    print("full")

Upvotes: 1

Related Questions