2017-03-01 63 views
5

問題1:我如何檢查是否一個完整的.xls或.csv文件empty.This是我使用的代碼:如何檢查是否.xls和.csv文件將空

try: 
    if os.stat(fullpath).st_size > 0: 
     readfile(fullpath) 
    else: 
     print "empty file" 
except OSError: 
    print "No file" 

的空的.xls文件的大小大於5.6kb,因此它是否具有任何內容並不明顯。 如何檢查xls或csv文件是否爲空?

問題2:我需要檢查文件的標題。 我怎麼能告訴python只有一行標題的文件是空的?

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. 

這是我的嘗試。我如何繼續使用此代碼?

請爲這兩個問題提供解決方案。提前致謝。

回答

5

這對於使用.empty方法的熊貓來說很簡單。執行此

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. 

這也只有頭文件返回True作爲

>> df = pd.DataFrame(columns = ['A','B']) 
>> df.empty 
    True 
+0

感謝您的answer.and我使用xlrd,我不想安裝任何其它軟件包像熊貓 –

1

我不認爲允許#2 2提問的時間,但讓我給你我的回答對Excel的部分

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 

關於標題:讓我給你一個小提示,測試sheet.nrows == 1

+0

ü說,檢查在同一時間的所有工作表。但如果片材1的數據和sheet2是空的。那麼我能做什麼。 –

+0

@bobmarti你是什麼意思?我們不知道你想做什麼!你只想要有沒有空的牀單? – Elmex80s

+0

我想檢查所有的牀單和空白的牀單視爲空和牀單值存儲到db –

2

問題1:我如何檢查整個.xls文件是空的。

def readfile(fullpath) 
    xls = xlrd.open_workbook(fullpath) 

    is_empty = None 

    for sheet in xls.sheets(): 
     number_of_rows = sheet.nrows 

     if number_of_rows == 1: 
      header = sheet.row_values(0) 
      # then If it contains only headers I want to treat as empty 
      if header: 
       is_empty = False 
       break 

     if number_of_rows > 1: 
      is_empty = False 
      break 

     number_of_columns = sheet.ncols 
     sheetname = sheet.name 

    if is_empty: 
     print('xlsx ist empty') 

問題2:我如何檢查文件的頭。如果該文件只有一個頭(我的意思是隻有一行),我需要把該文件是空的。怎麼我可以做那。

import csv 
with open('test/empty.csv', 'r') as csvfile: 
    csv_dict = [row for row in csv.DictReader(csvfile)] 
    if len(csv_dict) == 0: 
     print('csv file is empty') 

測試使用Python 3.4.2

+0

可能是你的答案是正確的,但我需要檢查csv ans xls –

+0

對於csv,你不需要迭代所有行,也不需要用DictReader解析。您可以檢查文件的第二行是否爲空。 'f.readline()== b'''。查看我的答案完整的例子。 – tsh

1

對於您的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) 
1

怎麼樣這樣的:

file = open(path, "r") 
file_content = file.read() 
file.close() 
if file_content == "": 
    print("File '{}' is empty".format(path)) 
else: 
    rows = file_content.split("\n", 1) 
    if rows[1] == "": 
     print("File '{}' contains headers only.".format(path)) 

其中path是您的XLS或CSV文件的路徑。

+0

Aftermind後,我不確定此代碼是否適用於xls文件,因爲此文件格式的特殊編碼... – PurpleJo

+0

它不起作用xls –

0

對於你的問題:

問題2:我需要檢查的文件頭。我怎麼能告訴python只有一行標題的文件是空的?

您可以檢查文件中的行。

with open('empty_csv_with_header.csv') as f: 
    f.readline() # skip header 
    line = f.readline() 
    if line == b'': 
     print('Empty csv')