For your excel code, I like the pandas solution someone came up with, but if you are at work and cannot install it, then I think you were almost there with the code approach that you took. You have a loop running through each sheet. This way you can test the rows on each sheet and then take the appropriate action if they are empty:
import xlrd xlFile = "MostlyEmptyBook.xlsx" def readfile(xlFile): xls=xlrd.open_workbook(xlFile) for sheet in xls.sheets(): number_of_rows = sheet.nrows number_of_columns = sheet.ncols sheetname = sheet.name header = sheet.row_values(0)
Note. I added a variable for the file name to make it easier to change it in one place throughout the code when using it. I also added : in your ad function that lacked it. If you want the test to have only a title (mine includes a completely blank page), change <= to == .
Regarding the related csv problem. csv is just a text file. We can be pretty sure that the file is empty except for the header using an encoding approach similar to the one that follows. I would try this code on sample files, and you can customize my math logic. For example, it may be sufficient to use + 1 to compare if instead of *1.5 , as I did. I think this is a space, or if several characters were mistakenly included, it will be a good cushion of file size + characters on the second line test specified in the encoding logic.
This was written under the assumption that you want to know if a file is empty before you download a giant file to your computer. If this assumption is not correct, you can use my test logic and then keep the file open or even read it in another code to make sure there is no empty line followed by additional content after the header (in a poorly formatted input file)
import os def convert_bytes(num): """ this function will convert bytes to MB.... GB... etc """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f %s" % (num, x) num /= 1024.0 def file_size(file_path): """ this function will return the file size """ if os.path.isfile(file_path): file_info = os.stat(file_path) return convert_bytes(file_info.st_size)
During testing, readline commands extract this content from a file:
['year,sex,births\n', '']
sample output:
[True, 16, 0, '17.0 bytes']
This approach means that you can access test results that are True / False in the [0] element of the list that it returns. Additional elements allow you to receive information about the inputs to the decision-making process for programs if you want to configure it later.
This code starts with a custom file size function. You can probably replace this depending on your preference if you are looking for shorter code. This will replace the first two tiny functions:
import os os.path.getsize(fullpathhere)