有没有办法检查一行是否有值?

2024-03-28 17:09:40 发布

您现在位置:Python中文网/ 问答频道 /正文

excel文件中有两列。一个是课程名称,另一个是学生在该课程中的成绩。有些课程前面没有成绩。有没有办法检查那个单元格是不是空的?你知道吗


Tags: 文件excel学生课程办法成绩课程名称
2条回答

你可以用搜索引擎检查它

示例:

from re import search

文件类似于列中的示例

+    -+    +
| Student | Score  |
|    -|    |        
|         |        |
| John    |   9    |
|         |        |
| Katty   |   7    |
|         |        |
| Alexnder|   8    |
|         |        |
|         |        |
| Bob     |        | #Empty
+         +

仅举个例子,我想搜索鲍勃的分数 我会打开文件

f = open('filename', 'r').readlines()
for d in f:
   column = d.rstrip()

现在我将开始搜索Bob的结果

   g = search(r'| Bob     |   (.*)    |', column)
   result = g.group(1)
   if result = '':
      print "Result Of Bob Is Empty"
   else:
      print "Result Of Bob Is : " + result

我制作了一个具有以下值的虚拟xlsx:

Course  | Grade
Maths   |
English | A
Science | B

使用openpyxl,并假设excel文件中的第二列是成绩,并且它只有一个工作表:

>>> from openpyxl import Workbook, load_workbook
>>> wb = load_workbook('Grades.xlsx')
>>> ws = wb.active
>>> for row in range(2,ws.max_row+1):
...     if not ws[row][1].value:
...             print([x.value for x in ws[row]])
...
[u'Maths', None]

以及xlrd使用具有相同值的xls文件:

>>> import xlrd
>>> wb = xlrd.open_workbook('Grades.xls')
>>> ws = wb.sheet_by_index(0)
>>> for row in range(1, ws.nrows):
...     if not ws.cell_value(row, 1):
...             print([ws.cell_value(row,0),ws.cell_value(row,1)])
...
[u'Maths', u'']

相关问题 更多 >