【问题标题】:Add file name and number of rows to Python dictionary [duplicate]将文件名和行数添加到 Python 字典 [重复]
【发布时间】:2022-01-12 21:55:13
【问题描述】:

这是我的第一篇文章 :)。我必须检查每个 csv 是否包含数据 - 因此行数 > 1(占标题)。

我因此试图附加到一个 dic

  • 文件名
  • 行数

到目前为止,我在我的 dict 中获得了文件的名称,但不是行数,而是路径的长度 + 文件名

import glob
import csv

all_files = glob.glob(path + '*.csv')

dic = {}

for file in all_files:
    dic[file] = len(list(csv.reader(file)))

非常感谢大家!

【问题讨论】:

    标签: python csv dictionary for-loop


    【解决方案1】:

    我认为这个问题已经在here@Metapod 对您的问题发表评论时得到了回答。

    简而言之,您应该使用sum() 方法来有效地计算行数:

    for file in all_files:
        dic[file] = sum(1 for row in(csv.reader(file)))
    

    【讨论】:

      猜你喜欢
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 2011-08-25
      • 1970-01-01
      • 2016-04-14
      相关资源
      最近更新 更多