如何检查 .xls 和 .csv 文件是否为空 [英] How to check if .xls and .csv files are empty
问题描述
问题 1:如何检查整个 .xls 或 .csv 文件是否为空.这是我使用的代码:
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"
一个空的 .xls 文件的大小大于 5.6kb,所以它是否有任何内容并不明显.如何检查 xls 或 csv 文件是否为空?
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?
问题 2:我需要检查文件的标题.如何告诉 python 只有一行标题的文件是空的?
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.
推荐答案
这在 Pandas 中很简单,.empty 方法.这样做
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.
对于只有标题的文件,这也将返回 True
This will also return True for a file with only headers as in
>> df = pd.DataFrame(columns = ['A','B'])
>> df.empty
True
这篇关于如何检查 .xls 和 .csv 文件是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!