Question 1: How can I check if an entire .xls or .csv file is empty.This is the code I am using:
try:
if os.stat(fullpath).st_size > 0:
readfile(fullpath)
else:
print "empty file"
except OSError:
print "No file"
An empty .xls file has size greater than 5.6kb so it is not obvious whether it has any contents. How can I check if an xls or csv file is empty?
Question 2: I need to check the header of the file. How can I tell python that files which are just a single row of headers are empty?
import xlrd
def readfile(fullpath)
xls=xlrd.open_workbook(fullpath)
for sheet in xls.sheets():
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
sheetname = sheet.name
header = sheet.row_values(0) #Then if it contains only headers, treat it as empty.
This is my attempt. How do I continue with this code?
Please provide a solution for both questions. Thanks in advance.
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