对于您的 excel 代码,我喜欢有人提出的 pandas 解决方案,但是如果您在工作并且无法安装它,那么我认为您几乎可以使用您所采用的代码方法。您有一个遍历每张纸的循环。因此,您可以测试每张工作表中的行,然后在为空时采取适当的措施,如下所示:
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) #then If it contains only headers I want to treat as empty
if number_of_rows <= 1:
# sheet is empty or has just a header
# do what you want here
print(xlFile + "is empty.")
注意:我为文件名添加了一个变量,以便在使用时更容易在整个代码中的一个位置进行更改。我还在你的函数声明中添加了:,但它缺少它。如果您希望测试只有标题(我的包含完全空白页),则将 <= 更改为 ==。
关于相关的 csv 问题。 csv 只是一个文本文件。我们可以合理地确定一个文件是空的,除了标题使用如下编码方法。我会在文件样本上尝试这段代码,你可能想调整我的数学逻辑。例如,在 if 比较中使用 + 1 而不是我所拥有的 *1.5 可能就足够了。我的想法是使用空格,或者如果错误地包含了一些字符,这将是一个很好的文件大小缓冲 + 编码逻辑中给出的第二行测试中的字符。
这是假设您想在将一些大文件加载到计算机之前知道文件是否为空的假设。如果该假设是错误的,您可以使用我的测试逻辑,然后保持文件打开,甚至读入更多代码以确保在标题之后没有空行后跟其他内容(在格式错误的输入文件中) :
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)
# testing if a csv file is empty in Python (header has bytes so not zero)
fileToTest = "almostEmptyCSV.csv"
def hasContentBeyondHeader(fileToTest):
answer = [ True, 0, 0, 0]
with open(fileToTest) as f:
lis = [ f.readline(), f.readline() ]
answer[1] = len(lis[0]) # length header row
answer[2] = len(lis[1]) # length of next row
answer[3] = file_size(fileToTest) # size of file
# these conditions should be high confidence file is empty or nearly so
sizeMult = 1.5 # test w/ your files and adjust as appropriate (but should work)
charLimit = 5
if answer[1] * sizeMult > answer[2] and answer[2] == 0:
answer[0] = False
elif answer[1] * sizeMult > answer[2] and answer[2] < charLimit:
# separate condition in case you want to remove it
# returns False if only a small number of chars (charLimit) on 2nd row
answer[0] = False
else:
answer[0] = True # added for readability (or delete else and keep default)
f.close()
return answer
hasContentBeyondHeader(fileToTest) # False if believed to be empty except for header
在测试期间,readline 命令从文件中提取了以下内容:
['year,sex,births\n', '']
样本输出:
[True, 16, 0, '17.0 bytes']
这种方法意味着您可以在它返回的列表的[0] 元素中访问真/假的测试结果。附加元素使您可以获取有关程序决策输入的信息,以防您以后想对其进行调整。
此代码以自定义文件大小函数开头。如果您正在寻找更短的代码,您可能可以根据您的喜好将其替换为这个。这将取代前两个小函数:
import os
os.path.getsize(fullpathhere)