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

问题描述 投票:0回答:3

如何计算文件夹中每个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
3个回答
1
投票

如果您不需要验证CSV内容或处理边缘情况(丢弃一些不同数量的行作为标题等),那么您根本不需要阅读CSV。 len(open(file).readlines())将为您计算每个文件中的行数。


1
投票

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

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:

0
投票

这段代码应该这样做

import os
import glob

path = "/home/.."
os.chdir(path)
result = [i for i in glob.glob('*.{}'.format("csv"))]

for i in result:
   with open(i, 'r', encoding="latin-1") as csvfile:
    print(i, ": ", str(len(csvfile.readlines()) - 1))
© www.soinside.com 2019 - 2024. All rights reserved.