bob*_*rti 7 python csv xls xlrd python-2.7
问题1:如何检查整个.xls或.csv文件是否为空.这是我使用的代码:
try:
if os.stat(fullpath).st_size > 0:
readfile(fullpath)
else:
print "empty file"
except OSError:
print "No file"
Run Code Online (Sandbox Code Playgroud)
空的.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.
Run Code Online (Sandbox Code Playgroud)
这是我的尝试.如何继续使用此代码?
请为这两个问题提供解决方案.提前致谢.
使用.empty方法在pandas中这很简单.做这个
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.
Run Code Online (Sandbox Code Playgroud)
对于仅包含标题的文件,这也将返回True
>> df = pd.DataFrame(columns = ['A','B'])
>> df.empty
True
Run Code Online (Sandbox Code Playgroud)
问题 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')
Run Code Online (Sandbox Code Playgroud)
问题 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')
Run Code Online (Sandbox Code Playgroud)
使用Python测试:3.4.2