close

How to check if .xls and .csv files are empty

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to check if .xls and .csv files are empty in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to check if .xls and .csv files are empty?

  1. How to check if .xls and .csv files are empty?

    I don't think Stackoverflow allows 2 question at the time but let me give you my answer for the Excel part

  2. check if .xls and .csv files are empty

    I don't think Stackoverflow allows 2 question at the time but let me give you my answer for the Excel part

Method 1

This is simple in pandas with the .empty method. Do this

import pandas as pd

df = pd.read_csv(filename) # or pd.read_excel(filename) for xls file
df.empty # will return True if the dataframe is empty or False if not.
This will also return True for a file with only headers as in

df = pd.DataFrame(columns = [‘A’,’B’])
df.empty
True

Method 2

I don’t think Stackoverflow allows 2 question at the time but let me give you my answer for the Excel part

import xlrd
from pprint import pprint

wb = xlrd.open_workbook("temp.xlsx")

empty_sheets = [sheet for sheet in wb.sheets() if sheet.ncols == 0]
non_empty_sheets = [sheet for sheet in wb.sheets() if sheet.ncols > 0]

# printing names of empty sheets
pprint([sheet.name for sheet in empty_sheets])

# writing non empty sheets to database 
pass # write code yourself or ask another question 

About the header: let me give you a little hint, test for sheet.nrows == 1.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read