Reputation: 995
I have a scenario which i am trying to implement , where i need to check file is empty or not But need to consider below case statements
Case 1 : if file as empty lines and no records then message should be shown as File is Empty
Case 2 : if file as Only Spaces and no records then message should be shown as File is Empty
Case 3 : if file as Only tabs and no records then message should be shown as File is Empty
I have tried my below code , but not satisfying
My python code :
import os
def isEmp(fname):
with open(fname) as f:
f.seek(0, os.SEEK_END)
if f.tell():
f.seek(0)
else:
print('File is Empty')
Any approach to cover all above Cases 1,2,3
Upvotes: 1
Views: 59
Reputation: 6017
def isEmp(fname):
with open(fname) as f:
contents = f.read().strip()
if contents:
# use contents here
print("Not empty")
else:
print("Empty")
You need to use .strip()
to remove all the spaces or tabs at the beginning and the end of the file.
Upvotes: 2