codeholic24
codeholic24

Reputation: 995

not able to return file as empty in python

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

Answers (1)

Harshal Parekh
Harshal Parekh

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

Related Questions