對於您的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只是一個文本文件。我們可以合理地確定一個文件是空的,除了使用如下所示的編碼方法的頭文件。我會在一個文件樣本上嘗試這段代碼,你可能想調整我的數學邏輯。例如,如果比較使用+ 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]
元素中的True/False的測試結果。通過附加的元素,您可以獲得有關計劃決策的信息,以備日後調整。
此代碼以自定義文件大小函數開始。如果您正在尋找更短的代碼,您可以根據您的偏好使用此取代。這將替換第一個兩個小功能:
import os
os.path.getsize(fullpathhere)
感謝您的answer.and我使用xlrd,我不想安裝任何其它軟件包像熊貓 –