python - 使用 DictReader 计数

标签 python dictionary count

还是 Python 的新手,这是我已经取得的成就:

import csv
import sys
import os.path

#VARIABLES


reader = None
col_header = None
total_rows = None
rows = None

#METHODS


def read_csv(csv_file):
#Read and display CSV file w/ HEADERS
    global reader, col_header, total_rows, rows

#Open assign dictionaries to reader
    with open(csv_file, newline='') as csv_file:
        #restval = blank columns = - /// restkey = extra columns +
        reader = csv.DictReader(csv_file, fieldnames=None, restkey='+', restval='-', delimiter=',',
                                quotechar='"')

        try:
            col_header = reader.fieldnames
            print('The headers: ' + str(reader.fieldnames))
            for row in reader:
                print(row)

            #Calculate number of rows
            rows = list(reader)
            total_rows = len(rows)
        except csv.Error as e:
            sys.exit('file {}, line {}: {}'.format(csv_file, reader.line_num, e))


def calc_total_rows():
    print('\nTotal number of rows: ' + str(total_rows))

我的问题是,当我尝试计算行数时,结果为 0(不可能,因为 csv_file 包含 4 行并且它们打印在屏幕上。 我将“#Calculate number of rows”代码放在我的打印行循环上方并且它可以工作,但是这些行然后不打印。好像每个任务都在互相偷字典?我该如何解决这个问题?

最佳答案

问题在于 reader 对象在遍历 CSV 时表现得像一个文件。首先,您在 for 循环中进行迭代,并打印每一行。然后你尝试从剩下的内容创建一个列表——当你遍历整个文件时它现在是空的。这个空列表的长度是0。

试试这个:

rows = list(reader)
for row in rows:
    print(row)

total_rows = len(rows)

关于python - 使用 DictReader 计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21539460/

相关文章:

Python打包麻烦(ppt) : Getting error when trying to run my packaged project that uses a non-. 命令行下的py文件

python - 如何在 MNIST 上使用 tf.contrib.model_pruning?

java - 具有方便符号的键值集合

performance - MongoDB 'count()' 非常慢。我们如何改进/解决它?

php - 如果不匹配,Mysql Count 返回零

PostgreSQL - 选择多个最大计数

python - Python 的 eval() 有什么作用?

python - 使用python获取窗口内的本地鼠标位置

python - 是否有一行 python 代码来替换这个嵌套循环?

c++ - 对 map<string, vector<string>> 中的唯一值进行排序