首页 > 解决方案 > 使用 PYTHON 计算多个 excel 文件中的行总和

问题描述

第 1 部分)我在文件夹路径中保存了多个 XLXS excel 文件:

文件名 行数 Excel 1 10 Excel 2 20 Excel 3 10 Excel 4 10 Excel 5 5

每个 XLXS 文件都包含相同的列,例如:姓名、邮政编码、地址、号码

每个都有不同的行数

我需要一种快速的方法来对 PYTHON 上这 5 个 Excel 文件中的所有行进行计数和求和。(我是手动完成的,我从未使用过 Python,需要在 Python 上执行此操作)

期望的输出应该是:

总数= 55

第 2 部分) 现在我有了总计数,我需要比较记录的计数,以确保它们在另一个单独的 **** 文件(组合 5 个 xlxs 文件)中相同 -

它应该都匹配到 55 行

标签: pythonexcelcountsumrow

解决方案


如果文件扩展名为 .csv、.tsv,则此脚本应该执行您想要的操作,例如:

sm=0
for i in range(1,6):
  lines = len(open("Excel {}".format(i)).readlines())
  print("Lines for Excel {} = {}".format(i, lines))
  sm = sm + lines

print("Sum of all lines = {}".format(sm))

编辑:由于它是 .xlsx 文件,因此您必须使用xlrd库:

import xlrd

sm=0
for i in range(1,6):
  lines = xlrd.open_workbook("Excel {}".format(i)).sheet_by_index(0).nrows
  print("Lines for Excel {} = {}".format(i, lines))
  sm = sm + lines

print("Sum of all lines = {}".format(sm))


推荐阅读