首页 > 解决方案 > 计算文件夹中每个 csv 文件的行数

问题描述

如何计算文件夹中每个 csv 文件的行数?

with open('filename.csv', 'r', encoding="latin-1") as csvfile:
    readCSV=csv.reader(csvfile, delimiter=',')

row_count=sum(1 for row in readCSV)
print(row_count)
for row in readCSV:
   print(row[1])

我为一个文件尝试了此操作,但我想为每个文件执行此操作,并且有很多..

import os
a ="foldername"
os.listdir(a)

我试过这个,但我不知道它是怎么回事..我对python真的很陌生..

非常感谢。

标签: python

解决方案


假设文件放在一个文件夹中:

import os
path = '/some/path/to/file'
for filename in os.listdir(path):
    with open(filename, 'r', encoding="latin-1") as fileObj:
        # -1 to exclude the header
        print("Rows Counted {} in the csv {}:".format(len(fileObj.readlines()) - 1, filename))  

输出(已测试):

Rows Counted 198 in the csv celebList.xlsx:
Rows Counted 148 in the csv cel_lis.xls:

推荐阅读