简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM