1

I have so many CSV files in a particular folder. So i just want to check which CSV file is empty and if any csv file is empty print that file name also. And Some files may be contain only header part. So this type file will also be empty file. I need to print that file also.

     try:
        path = '/nsmnt/NS_Exec_DSHBD/output/*.csv'
        files = glob.glob(path)
        for name in files:
            with open(name, 'r') as csvfile:
                csvreader = csv.reader(csvfile)
                for row in csvreader:
                    #print(row)
                    if row[0] == 'NULL':
                        print("file is empty!")
                        print(name)

    except Exception as ex:
        print(ex)
amisha
  • 49
  • 2
  • 8
  • 7
    Possible duplicate of [How to check whether a file is empty or not?](https://stackoverflow.com/questions/2507808/how-to-check-whether-a-file-is-empty-or-not) – Ajay Singh Apr 03 '19 at 12:22
  • 3
    Not a duplicate after the update: header-only file is also considered empty in this case. – bereal Apr 03 '19 at 12:32

1 Answers1

3

The question boils down to how to find out if a file has at most one row (which is a header).

def is_empty_csv(path):
    with open(name) as csvfile:
        reader = csv.reader(csvfile)
        for i, _ in enumerate(reader):
            if i:  # found the second row
                return False
    return True
bereal
  • 32,519
  • 6
  • 58
  • 104