1

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

2
  • 2
    if not f.read().strip(): print('File is empty') Commented Jul 23, 2021 at 14:44
  • if not f.read.strip(), a non empty string is truth value so an empty string is false. if not True which is if False, the string is empty so print('Empty file') Commented Jul 23, 2021 at 14:50

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

4 Comments

You should check if len(contents) > 0. Using strip() will just return an empty string if the file is all spaces.
if contents: will return False if the string is empty
@Harshal Parekh Thanks it seems the not_speshal comment should be consider I believe
In the code provided, all the 3 cases will work just fine @codeholic24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.